agora inbox for [email protected]help / color / mirror / Atom feed
[PATCH v23 7/8] Row pattern recognition patch (tests). 165+ messages / 2 participants [nested] [flat]
* [PATCH v23 7/8] Row pattern recognition patch (tests). @ 2024-10-25 03:56 Tatsuo Ishii <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Tatsuo Ishii @ 2024-10-25 03:56 UTC (permalink / raw) --- src/test/regress/expected/rpr.out | 919 +++++++++++++++++++++++++++++ src/test/regress/parallel_schedule | 2 +- src/test/regress/sql/rpr.sql | 467 +++++++++++++++ 3 files changed, 1387 insertions(+), 1 deletion(-) create mode 100644 src/test/regress/expected/rpr.out create mode 100644 src/test/regress/sql/rpr.sql diff --git a/src/test/regress/expected/rpr.out b/src/test/regress/expected/rpr.out new file mode 100644 index 0000000000..b8cd6190b4 --- /dev/null +++ b/src/test/regress/expected/rpr.out @@ -0,0 +1,919 @@ +-- +-- Test for row pattern definition clause +-- +CREATE TEMP TABLE stock ( + company TEXT, + tdate DATE, + price INTEGER +); +INSERT INTO stock VALUES ('company1', '2023-07-01', 100); +INSERT INTO stock VALUES ('company1', '2023-07-02', 200); +INSERT INTO stock VALUES ('company1', '2023-07-03', 150); +INSERT INTO stock VALUES ('company1', '2023-07-04', 140); +INSERT INTO stock VALUES ('company1', '2023-07-05', 150); +INSERT INTO stock VALUES ('company1', '2023-07-06', 90); +INSERT INTO stock VALUES ('company1', '2023-07-07', 110); +INSERT INTO stock VALUES ('company1', '2023-07-08', 130); +INSERT INTO stock VALUES ('company1', '2023-07-09', 120); +INSERT INTO stock VALUES ('company1', '2023-07-10', 130); +INSERT INTO stock VALUES ('company2', '2023-07-01', 50); +INSERT INTO stock VALUES ('company2', '2023-07-02', 2000); +INSERT INTO stock VALUES ('company2', '2023-07-03', 1500); +INSERT INTO stock VALUES ('company2', '2023-07-04', 1400); +INSERT INTO stock VALUES ('company2', '2023-07-05', 1500); +INSERT INTO stock VALUES ('company2', '2023-07-06', 60); +INSERT INTO stock VALUES ('company2', '2023-07-07', 1100); +INSERT INTO stock VALUES ('company2', '2023-07-08', 1300); +INSERT INTO stock VALUES ('company2', '2023-07-09', 1200); +INSERT INTO stock VALUES ('company2', '2023-07-10', 1300); +SELECT * FROM stock; + company | tdate | price +----------+------------+------- + company1 | 07-01-2023 | 100 + company1 | 07-02-2023 | 200 + company1 | 07-03-2023 | 150 + company1 | 07-04-2023 | 140 + company1 | 07-05-2023 | 150 + company1 | 07-06-2023 | 90 + company1 | 07-07-2023 | 110 + company1 | 07-08-2023 | 130 + company1 | 07-09-2023 | 120 + company1 | 07-10-2023 | 130 + company2 | 07-01-2023 | 50 + company2 | 07-02-2023 | 2000 + company2 | 07-03-2023 | 1500 + company2 | 07-04-2023 | 1400 + company2 | 07-05-2023 | 1500 + company2 | 07-06-2023 | 60 + company2 | 07-07-2023 | 1100 + company2 | 07-08-2023 | 1300 + company2 | 07-09-2023 | 1200 + company2 | 07-10-2023 | 1300 +(20 rows) + +-- basic test using PREV +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w, + nth_value(tdate, 2) OVER w AS nth_second + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + company | tdate | price | first_value | last_value | nth_second +----------+------------+-------+-------------+------------+------------ + company1 | 07-01-2023 | 100 | 100 | 140 | 07-02-2023 + company1 | 07-02-2023 | 200 | | | + company1 | 07-03-2023 | 150 | | | + company1 | 07-04-2023 | 140 | | | + company1 | 07-05-2023 | 150 | | | + company1 | 07-06-2023 | 90 | 90 | 120 | 07-07-2023 + company1 | 07-07-2023 | 110 | | | + company1 | 07-08-2023 | 130 | | | + company1 | 07-09-2023 | 120 | | | + company1 | 07-10-2023 | 130 | | | + company2 | 07-01-2023 | 50 | 50 | 1400 | 07-02-2023 + company2 | 07-02-2023 | 2000 | | | + company2 | 07-03-2023 | 1500 | | | + company2 | 07-04-2023 | 1400 | | | + company2 | 07-05-2023 | 1500 | | | + company2 | 07-06-2023 | 60 | 60 | 1200 | 07-07-2023 + company2 | 07-07-2023 | 1100 | | | + company2 | 07-08-2023 | 1300 | | | + company2 | 07-09-2023 | 1200 | | | + company2 | 07-10-2023 | 1300 | | | +(20 rows) + +-- basic test using PREV. UP appears twice +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w, + nth_value(tdate, 2) OVER w AS nth_second + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+ UP+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + company | tdate | price | first_value | last_value | nth_second +----------+------------+-------+-------------+------------+------------ + company1 | 07-01-2023 | 100 | 100 | 150 | 07-02-2023 + company1 | 07-02-2023 | 200 | | | + company1 | 07-03-2023 | 150 | | | + company1 | 07-04-2023 | 140 | | | + company1 | 07-05-2023 | 150 | | | + company1 | 07-06-2023 | 90 | 90 | 130 | 07-07-2023 + company1 | 07-07-2023 | 110 | | | + company1 | 07-08-2023 | 130 | | | + company1 | 07-09-2023 | 120 | | | + company1 | 07-10-2023 | 130 | | | + company2 | 07-01-2023 | 50 | 50 | 1500 | 07-02-2023 + company2 | 07-02-2023 | 2000 | | | + company2 | 07-03-2023 | 1500 | | | + company2 | 07-04-2023 | 1400 | | | + company2 | 07-05-2023 | 1500 | | | + company2 | 07-06-2023 | 60 | 60 | 1300 | 07-07-2023 + company2 | 07-07-2023 | 1100 | | | + company2 | 07-08-2023 | 1300 | | | + company2 | 07-09-2023 | 1200 | | | + company2 | 07-10-2023 | 1300 | | | +(20 rows) + +-- basic test using PREV. Use '*' +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w, + nth_value(tdate, 2) OVER w AS nth_second + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP* DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + company | tdate | price | first_value | last_value | nth_second +----------+------------+-------+-------------+------------+------------ + company1 | 07-01-2023 | 100 | 100 | 140 | 07-02-2023 + company1 | 07-02-2023 | 200 | | | + company1 | 07-03-2023 | 150 | | | + company1 | 07-04-2023 | 140 | | | + company1 | 07-05-2023 | 150 | 150 | 90 | 07-06-2023 + company1 | 07-06-2023 | 90 | | | + company1 | 07-07-2023 | 110 | 110 | 120 | 07-08-2023 + company1 | 07-08-2023 | 130 | | | + company1 | 07-09-2023 | 120 | | | + company1 | 07-10-2023 | 130 | | | + company2 | 07-01-2023 | 50 | 50 | 1400 | 07-02-2023 + company2 | 07-02-2023 | 2000 | | | + company2 | 07-03-2023 | 1500 | | | + company2 | 07-04-2023 | 1400 | | | + company2 | 07-05-2023 | 1500 | 1500 | 60 | 07-06-2023 + company2 | 07-06-2023 | 60 | | | + company2 | 07-07-2023 | 1100 | 1100 | 1200 | 07-08-2023 + company2 | 07-08-2023 | 1300 | | | + company2 | 07-09-2023 | 1200 | | | + company2 | 07-10-2023 | 1300 | | | +(20 rows) + +-- basic test with none greedy pattern +SELECT company, tdate, price, count(*) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (A A A) + DEFINE + A AS price >= 140 AND price <= 150 +); + company | tdate | price | count +----------+------------+-------+------- + company1 | 07-01-2023 | 100 | 0 + company1 | 07-02-2023 | 200 | 0 + company1 | 07-03-2023 | 150 | 3 + company1 | 07-04-2023 | 140 | 0 + company1 | 07-05-2023 | 150 | 0 + company1 | 07-06-2023 | 90 | 0 + company1 | 07-07-2023 | 110 | 0 + company1 | 07-08-2023 | 130 | 0 + company1 | 07-09-2023 | 120 | 0 + company1 | 07-10-2023 | 130 | 0 + company2 | 07-01-2023 | 50 | 0 + company2 | 07-02-2023 | 2000 | 0 + company2 | 07-03-2023 | 1500 | 0 + company2 | 07-04-2023 | 1400 | 0 + company2 | 07-05-2023 | 1500 | 0 + company2 | 07-06-2023 | 60 | 0 + company2 | 07-07-2023 | 1100 | 0 + company2 | 07-08-2023 | 1300 | 0 + company2 | 07-09-2023 | 1200 | 0 + company2 | 07-10-2023 | 1300 | 0 +(20 rows) + +-- last_value() should remain consistent +SELECT company, tdate, price, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + company | tdate | price | last_value +----------+------------+-------+------------ + company1 | 07-01-2023 | 100 | 140 + company1 | 07-02-2023 | 200 | + company1 | 07-03-2023 | 150 | + company1 | 07-04-2023 | 140 | + company1 | 07-05-2023 | 150 | + company1 | 07-06-2023 | 90 | 120 + company1 | 07-07-2023 | 110 | + company1 | 07-08-2023 | 130 | + company1 | 07-09-2023 | 120 | + company1 | 07-10-2023 | 130 | + company2 | 07-01-2023 | 50 | 1400 + company2 | 07-02-2023 | 2000 | + company2 | 07-03-2023 | 1500 | + company2 | 07-04-2023 | 1400 | + company2 | 07-05-2023 | 1500 | + company2 | 07-06-2023 | 60 | 1200 + company2 | 07-07-2023 | 1100 | + company2 | 07-08-2023 | 1300 | + company2 | 07-09-2023 | 1200 | + company2 | 07-10-2023 | 1300 | +(20 rows) + +-- omit "START" in DEFINE but it is ok because "START AS TRUE" is +-- implicitly defined. per spec. +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w, + nth_value(tdate, 2) OVER w AS nth_second + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + company | tdate | price | first_value | last_value | nth_second +----------+------------+-------+-------------+------------+------------ + company1 | 07-01-2023 | 100 | 100 | 140 | 07-02-2023 + company1 | 07-02-2023 | 200 | | | + company1 | 07-03-2023 | 150 | | | + company1 | 07-04-2023 | 140 | | | + company1 | 07-05-2023 | 150 | | | + company1 | 07-06-2023 | 90 | 90 | 120 | 07-07-2023 + company1 | 07-07-2023 | 110 | | | + company1 | 07-08-2023 | 130 | | | + company1 | 07-09-2023 | 120 | | | + company1 | 07-10-2023 | 130 | | | + company2 | 07-01-2023 | 50 | 50 | 1400 | 07-02-2023 + company2 | 07-02-2023 | 2000 | | | + company2 | 07-03-2023 | 1500 | | | + company2 | 07-04-2023 | 1400 | | | + company2 | 07-05-2023 | 1500 | | | + company2 | 07-06-2023 | 60 | 60 | 1200 | 07-07-2023 + company2 | 07-07-2023 | 1100 | | | + company2 | 07-08-2023 | 1300 | | | + company2 | 07-09-2023 | 1200 | | | + company2 | 07-10-2023 | 1300 | | | +(20 rows) + +-- the first row start with less than or equal to 100 +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (LOWPRICE UP+ DOWN+) + DEFINE + LOWPRICE AS price <= 100, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + company | tdate | price | first_value | last_value +----------+------------+-------+-------------+------------ + company1 | 07-01-2023 | 100 | 100 | 140 + company1 | 07-02-2023 | 200 | | + company1 | 07-03-2023 | 150 | | + company1 | 07-04-2023 | 140 | | + company1 | 07-05-2023 | 150 | | + company1 | 07-06-2023 | 90 | 90 | 120 + company1 | 07-07-2023 | 110 | | + company1 | 07-08-2023 | 130 | | + company1 | 07-09-2023 | 120 | | + company1 | 07-10-2023 | 130 | | + company2 | 07-01-2023 | 50 | 50 | 1400 + company2 | 07-02-2023 | 2000 | | + company2 | 07-03-2023 | 1500 | | + company2 | 07-04-2023 | 1400 | | + company2 | 07-05-2023 | 1500 | | + company2 | 07-06-2023 | 60 | 60 | 1200 + company2 | 07-07-2023 | 1100 | | + company2 | 07-08-2023 | 1300 | | + company2 | 07-09-2023 | 1200 | | + company2 | 07-10-2023 | 1300 | | +(20 rows) + +-- second row raises 120% +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (LOWPRICE UP+ DOWN+) + DEFINE + LOWPRICE AS price <= 100, + UP AS price > PREV(price) * 1.2, + DOWN AS price < PREV(price) +); + company | tdate | price | first_value | last_value +----------+------------+-------+-------------+------------ + company1 | 07-01-2023 | 100 | 100 | 140 + company1 | 07-02-2023 | 200 | | + company1 | 07-03-2023 | 150 | | + company1 | 07-04-2023 | 140 | | + company1 | 07-05-2023 | 150 | | + company1 | 07-06-2023 | 90 | | + company1 | 07-07-2023 | 110 | | + company1 | 07-08-2023 | 130 | | + company1 | 07-09-2023 | 120 | | + company1 | 07-10-2023 | 130 | | + company2 | 07-01-2023 | 50 | 50 | 1400 + company2 | 07-02-2023 | 2000 | | + company2 | 07-03-2023 | 1500 | | + company2 | 07-04-2023 | 1400 | | + company2 | 07-05-2023 | 1500 | | + company2 | 07-06-2023 | 60 | | + company2 | 07-07-2023 | 1100 | | + company2 | 07-08-2023 | 1300 | | + company2 | 07-09-2023 | 1200 | | + company2 | 07-10-2023 | 1300 | | +(20 rows) + +-- using NEXT +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UPDOWN) + DEFINE + START AS TRUE, + UPDOWN AS price > PREV(price) AND price > NEXT(price) +); + company | tdate | price | first_value | last_value +----------+------------+-------+-------------+------------ + company1 | 07-01-2023 | 100 | 100 | 200 + company1 | 07-02-2023 | 200 | | + company1 | 07-03-2023 | 150 | | + company1 | 07-04-2023 | 140 | 140 | 150 + company1 | 07-05-2023 | 150 | | + company1 | 07-06-2023 | 90 | | + company1 | 07-07-2023 | 110 | 110 | 130 + company1 | 07-08-2023 | 130 | | + company1 | 07-09-2023 | 120 | | + company1 | 07-10-2023 | 130 | | + company2 | 07-01-2023 | 50 | 50 | 2000 + company2 | 07-02-2023 | 2000 | | + company2 | 07-03-2023 | 1500 | | + company2 | 07-04-2023 | 1400 | 1400 | 1500 + company2 | 07-05-2023 | 1500 | | + company2 | 07-06-2023 | 60 | | + company2 | 07-07-2023 | 1100 | 1100 | 1300 + company2 | 07-08-2023 | 1300 | | + company2 | 07-09-2023 | 1200 | | + company2 | 07-10-2023 | 1300 | | +(20 rows) + +-- using AFTER MATCH SKIP TO NEXT ROW +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP TO NEXT ROW + INITIAL + PATTERN (START UPDOWN) + DEFINE + START AS TRUE, + UPDOWN AS price > PREV(price) AND price > NEXT(price) +); + company | tdate | price | first_value | last_value +----------+------------+-------+-------------+------------ + company1 | 07-01-2023 | 100 | 100 | 200 + company1 | 07-02-2023 | 200 | | + company1 | 07-03-2023 | 150 | | + company1 | 07-04-2023 | 140 | 140 | 150 + company1 | 07-05-2023 | 150 | | + company1 | 07-06-2023 | 90 | | + company1 | 07-07-2023 | 110 | 110 | 130 + company1 | 07-08-2023 | 130 | | + company1 | 07-09-2023 | 120 | | + company1 | 07-10-2023 | 130 | | + company2 | 07-01-2023 | 50 | 50 | 2000 + company2 | 07-02-2023 | 2000 | | + company2 | 07-03-2023 | 1500 | | + company2 | 07-04-2023 | 1400 | 1400 | 1500 + company2 | 07-05-2023 | 1500 | | + company2 | 07-06-2023 | 60 | | + company2 | 07-07-2023 | 1100 | 1100 | 1300 + company2 | 07-08-2023 | 1300 | | + company2 | 07-09-2023 | 1200 | | + company2 | 07-10-2023 | 1300 | | +(20 rows) + +-- match everything +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP PAST LAST ROW + INITIAL + PATTERN (A+) + DEFINE + A AS TRUE +); + company | tdate | price | first_value | last_value +----------+------------+-------+-------------+------------ + company1 | 07-01-2023 | 100 | 100 | 130 + company1 | 07-02-2023 | 200 | | + company1 | 07-03-2023 | 150 | | + company1 | 07-04-2023 | 140 | | + company1 | 07-05-2023 | 150 | | + company1 | 07-06-2023 | 90 | | + company1 | 07-07-2023 | 110 | | + company1 | 07-08-2023 | 130 | | + company1 | 07-09-2023 | 120 | | + company1 | 07-10-2023 | 130 | | + company2 | 07-01-2023 | 50 | 50 | 1300 + company2 | 07-02-2023 | 2000 | | + company2 | 07-03-2023 | 1500 | | + company2 | 07-04-2023 | 1400 | | + company2 | 07-05-2023 | 1500 | | + company2 | 07-06-2023 | 60 | | + company2 | 07-07-2023 | 1100 | | + company2 | 07-08-2023 | 1300 | | + company2 | 07-09-2023 | 1200 | | + company2 | 07-10-2023 | 1300 | | +(20 rows) + +-- backtracking with reclassification of rows +-- using AFTER MATCH SKIP PAST LAST ROW +SELECT company, tdate, price, first_value(tdate) OVER w, last_value(tdate) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP PAST LAST ROW + INITIAL + PATTERN (A+ B+) + DEFINE + A AS price > 100, + B AS price > 100 +); + company | tdate | price | first_value | last_value +----------+------------+-------+-------------+------------ + company1 | 07-01-2023 | 100 | | + company1 | 07-02-2023 | 200 | 07-02-2023 | 07-05-2023 + company1 | 07-03-2023 | 150 | | + company1 | 07-04-2023 | 140 | | + company1 | 07-05-2023 | 150 | | + company1 | 07-06-2023 | 90 | | + company1 | 07-07-2023 | 110 | 07-07-2023 | 07-10-2023 + company1 | 07-08-2023 | 130 | | + company1 | 07-09-2023 | 120 | | + company1 | 07-10-2023 | 130 | | + company2 | 07-01-2023 | 50 | | + company2 | 07-02-2023 | 2000 | 07-02-2023 | 07-05-2023 + company2 | 07-03-2023 | 1500 | | + company2 | 07-04-2023 | 1400 | | + company2 | 07-05-2023 | 1500 | | + company2 | 07-06-2023 | 60 | | + company2 | 07-07-2023 | 1100 | 07-07-2023 | 07-10-2023 + company2 | 07-08-2023 | 1300 | | + company2 | 07-09-2023 | 1200 | | + company2 | 07-10-2023 | 1300 | | +(20 rows) + +-- backtracking with reclassification of rows +-- using AFTER MATCH SKIP TO NEXT ROW +SELECT company, tdate, price, first_value(tdate) OVER w, last_value(tdate) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP TO NEXT ROW + INITIAL + PATTERN (A+ B+) + DEFINE + A AS price > 100, + B AS price > 100 +); + company | tdate | price | first_value | last_value +----------+------------+-------+-------------+------------ + company1 | 07-01-2023 | 100 | | + company1 | 07-02-2023 | 200 | 07-02-2023 | 07-05-2023 + company1 | 07-03-2023 | 150 | 07-03-2023 | 07-05-2023 + company1 | 07-04-2023 | 140 | 07-04-2023 | 07-05-2023 + company1 | 07-05-2023 | 150 | | + company1 | 07-06-2023 | 90 | | + company1 | 07-07-2023 | 110 | 07-07-2023 | 07-10-2023 + company1 | 07-08-2023 | 130 | 07-08-2023 | 07-10-2023 + company1 | 07-09-2023 | 120 | 07-09-2023 | 07-10-2023 + company1 | 07-10-2023 | 130 | | + company2 | 07-01-2023 | 50 | | + company2 | 07-02-2023 | 2000 | 07-02-2023 | 07-05-2023 + company2 | 07-03-2023 | 1500 | 07-03-2023 | 07-05-2023 + company2 | 07-04-2023 | 1400 | 07-04-2023 | 07-05-2023 + company2 | 07-05-2023 | 1500 | | + company2 | 07-06-2023 | 60 | | + company2 | 07-07-2023 | 1100 | 07-07-2023 | 07-10-2023 + company2 | 07-08-2023 | 1300 | 07-08-2023 | 07-10-2023 + company2 | 07-09-2023 | 1200 | 07-09-2023 | 07-10-2023 + company2 | 07-10-2023 | 1300 | | +(20 rows) + +-- ROWS BETWEEN CURRENT ROW AND offset FOLLOWING +SELECT company, tdate, price, first_value(tdate) OVER w, last_value(tdate) OVER w, + count(*) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING + AFTER MATCH SKIP PAST LAST ROW + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + company | tdate | price | first_value | last_value | count +----------+------------+-------+-------------+------------+------- + company1 | 07-01-2023 | 100 | 07-01-2023 | 07-03-2023 | 3 + company1 | 07-02-2023 | 200 | | | 0 + company1 | 07-03-2023 | 150 | | | 0 + company1 | 07-04-2023 | 140 | 07-04-2023 | 07-06-2023 | 3 + company1 | 07-05-2023 | 150 | | | 0 + company1 | 07-06-2023 | 90 | | | 0 + company1 | 07-07-2023 | 110 | 07-07-2023 | 07-09-2023 | 3 + company1 | 07-08-2023 | 130 | | | 0 + company1 | 07-09-2023 | 120 | | | 0 + company1 | 07-10-2023 | 130 | | | 0 + company2 | 07-01-2023 | 50 | 07-01-2023 | 07-03-2023 | 3 + company2 | 07-02-2023 | 2000 | | | 0 + company2 | 07-03-2023 | 1500 | | | 0 + company2 | 07-04-2023 | 1400 | 07-04-2023 | 07-06-2023 | 3 + company2 | 07-05-2023 | 1500 | | | 0 + company2 | 07-06-2023 | 60 | | | 0 + company2 | 07-07-2023 | 1100 | 07-07-2023 | 07-09-2023 | 3 + company2 | 07-08-2023 | 1300 | | | 0 + company2 | 07-09-2023 | 1200 | | | 0 + company2 | 07-10-2023 | 1300 | | | 0 +(20 rows) + +-- +-- Aggregates +-- +-- using AFTER MATCH SKIP PAST LAST ROW +SELECT company, tdate, price, + first_value(price) OVER w, + last_value(price) OVER w, + max(price) OVER w, + min(price) OVER w, + sum(price) OVER w, + avg(price) OVER w, + count(price) OVER w +FROM stock +WINDOW w AS ( +PARTITION BY company +ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING +AFTER MATCH SKIP PAST LAST ROW +INITIAL +PATTERN (START UP+ DOWN+) +DEFINE +START AS TRUE, +UP AS price > PREV(price), +DOWN AS price < PREV(price) +); + company | tdate | price | first_value | last_value | max | min | sum | avg | count +----------+------------+-------+-------------+------------+------+-----+------+-----------------------+------- + company1 | 07-01-2023 | 100 | 100 | 140 | 200 | 100 | 590 | 147.5000000000000000 | 4 + company1 | 07-02-2023 | 200 | | | | | | | 0 + company1 | 07-03-2023 | 150 | | | | | | | 0 + company1 | 07-04-2023 | 140 | | | | | | | 0 + company1 | 07-05-2023 | 150 | | | | | | | 0 + company1 | 07-06-2023 | 90 | 90 | 120 | 130 | 90 | 450 | 112.5000000000000000 | 4 + company1 | 07-07-2023 | 110 | | | | | | | 0 + company1 | 07-08-2023 | 130 | | | | | | | 0 + company1 | 07-09-2023 | 120 | | | | | | | 0 + company1 | 07-10-2023 | 130 | | | | | | | 0 + company2 | 07-01-2023 | 50 | 50 | 1400 | 2000 | 50 | 4950 | 1237.5000000000000000 | 4 + company2 | 07-02-2023 | 2000 | | | | | | | 0 + company2 | 07-03-2023 | 1500 | | | | | | | 0 + company2 | 07-04-2023 | 1400 | | | | | | | 0 + company2 | 07-05-2023 | 1500 | | | | | | | 0 + company2 | 07-06-2023 | 60 | 60 | 1200 | 1300 | 60 | 3660 | 915.0000000000000000 | 4 + company2 | 07-07-2023 | 1100 | | | | | | | 0 + company2 | 07-08-2023 | 1300 | | | | | | | 0 + company2 | 07-09-2023 | 1200 | | | | | | | 0 + company2 | 07-10-2023 | 1300 | | | | | | | 0 +(20 rows) + +-- using AFTER MATCH SKIP TO NEXT ROW +SELECT company, tdate, price, + first_value(price) OVER w, + last_value(price) OVER w, + max(price) OVER w, + min(price) OVER w, + sum(price) OVER w, + avg(price) OVER w, + count(price) OVER w +FROM stock +WINDOW w AS ( +PARTITION BY company +ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING +AFTER MATCH SKIP TO NEXT ROW +INITIAL +PATTERN (START UP+ DOWN+) +DEFINE +START AS TRUE, +UP AS price > PREV(price), +DOWN AS price < PREV(price) +); + company | tdate | price | first_value | last_value | max | min | sum | avg | count +----------+------------+-------+-------------+------------+------+------+------+-----------------------+------- + company1 | 07-01-2023 | 100 | 100 | 140 | 200 | 100 | 590 | 147.5000000000000000 | 4 + company1 | 07-02-2023 | 200 | | | | | | | 0 + company1 | 07-03-2023 | 150 | | | | | | | 0 + company1 | 07-04-2023 | 140 | 140 | 90 | 150 | 90 | 380 | 126.6666666666666667 | 3 + company1 | 07-05-2023 | 150 | | | | | | | 0 + company1 | 07-06-2023 | 90 | 90 | 120 | 130 | 90 | 450 | 112.5000000000000000 | 4 + company1 | 07-07-2023 | 110 | 110 | 120 | 130 | 110 | 360 | 120.0000000000000000 | 3 + company1 | 07-08-2023 | 130 | | | | | | | 0 + company1 | 07-09-2023 | 120 | | | | | | | 0 + company1 | 07-10-2023 | 130 | | | | | | | 0 + company2 | 07-01-2023 | 50 | 50 | 1400 | 2000 | 50 | 4950 | 1237.5000000000000000 | 4 + company2 | 07-02-2023 | 2000 | | | | | | | 0 + company2 | 07-03-2023 | 1500 | | | | | | | 0 + company2 | 07-04-2023 | 1400 | 1400 | 60 | 1500 | 60 | 2960 | 986.6666666666666667 | 3 + company2 | 07-05-2023 | 1500 | | | | | | | 0 + company2 | 07-06-2023 | 60 | 60 | 1200 | 1300 | 60 | 3660 | 915.0000000000000000 | 4 + company2 | 07-07-2023 | 1100 | 1100 | 1200 | 1300 | 1100 | 3600 | 1200.0000000000000000 | 3 + company2 | 07-08-2023 | 1300 | | | | | | | 0 + company2 | 07-09-2023 | 1200 | | | | | | | 0 + company2 | 07-10-2023 | 1300 | | | | | | | 0 +(20 rows) + +-- JOIN case +CREATE TEMP TABLE t1 (i int, v1 int); +CREATE TEMP TABLE t2 (j int, v2 int); +INSERT INTO t1 VALUES(1,10); +INSERT INTO t1 VALUES(1,11); +INSERT INTO t1 VALUES(1,12); +INSERT INTO t2 VALUES(2,10); +INSERT INTO t2 VALUES(2,11); +INSERT INTO t2 VALUES(2,12); +SELECT * FROM t1, t2 WHERE t1.v1 <= 11 AND t2.v2 <= 11; + i | v1 | j | v2 +---+----+---+---- + 1 | 10 | 2 | 10 + 1 | 10 | 2 | 11 + 1 | 11 | 2 | 10 + 1 | 11 | 2 | 11 +(4 rows) + +SELECT *, count(*) OVER w FROM t1, t2 +WINDOW w AS ( + PARTITION BY t1.i + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (A) + DEFINE + A AS v1 <= 11 AND v2 <= 11 +); + i | v1 | j | v2 | count +---+----+---+----+------- + 1 | 10 | 2 | 10 | 1 + 1 | 10 | 2 | 11 | 1 + 1 | 10 | 2 | 12 | 0 + 1 | 11 | 2 | 10 | 1 + 1 | 11 | 2 | 11 | 1 + 1 | 11 | 2 | 12 | 0 + 1 | 12 | 2 | 10 | 0 + 1 | 12 | 2 | 11 | 0 + 1 | 12 | 2 | 12 | 0 +(9 rows) + +-- WITH case +WITH wstock AS ( + SELECT * FROM stock WHERE tdate < '2023-07-08' +) +SELECT tdate, price, +first_value(tdate) OVER w, +count(*) OVER w + FROM wstock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + tdate | price | first_value | count +------------+-------+-------------+------- + 07-01-2023 | 100 | 07-01-2023 | 4 + 07-02-2023 | 200 | | 0 + 07-03-2023 | 150 | | 0 + 07-04-2023 | 140 | | 0 + 07-05-2023 | 150 | | 0 + 07-06-2023 | 90 | | 0 + 07-07-2023 | 110 | | 0 + 07-01-2023 | 50 | 07-01-2023 | 4 + 07-02-2023 | 2000 | | 0 + 07-03-2023 | 1500 | | 0 + 07-04-2023 | 1400 | | 0 + 07-05-2023 | 1500 | | 0 + 07-06-2023 | 60 | | 0 + 07-07-2023 | 1100 | | 0 +(14 rows) + +-- PREV has multiple column reference +CREATE TEMP TABLE rpr1 (id INTEGER, i SERIAL, j INTEGER); +INSERT INTO rpr1(id, j) SELECT 1, g*2 FROM generate_series(1, 10) AS g; +SELECT id, i, j, count(*) OVER w + FROM rpr1 + WINDOW w AS ( + PARTITION BY id + ORDER BY i + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP PAST LAST ROW + INITIAL + PATTERN (START COND+) + DEFINE + START AS TRUE, + COND AS PREV(i + j + 1) < 10 +); + id | i | j | count +----+----+----+------- + 1 | 1 | 2 | 3 + 1 | 2 | 4 | 0 + 1 | 3 | 6 | 0 + 1 | 4 | 8 | 0 + 1 | 5 | 10 | 0 + 1 | 6 | 12 | 0 + 1 | 7 | 14 | 0 + 1 | 8 | 16 | 0 + 1 | 9 | 18 | 0 + 1 | 10 | 20 | 0 +(10 rows) + +-- Smoke test for larger partitions. +WITH s AS ( + SELECT v, count(*) OVER w AS c + FROM (SELECT generate_series(1, 5000) v) + WINDOW w AS ( + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP PAST LAST ROW + INITIAL + PATTERN ( r+ ) + DEFINE r AS TRUE + ) +) +-- Should be exactly one long match across all rows. +SELECT * FROM s WHERE c > 0; + v | c +---+------ + 1 | 5000 +(1 row) + +WITH s AS ( + SELECT v, count(*) OVER w AS c + FROM (SELECT generate_series(1, 5000) v) + WINDOW w AS ( + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP PAST LAST ROW + INITIAL + PATTERN ( r ) + DEFINE r AS TRUE + ) +) +-- Every row should be its own match. +SELECT count(*) FROM s WHERE c > 0; + count +------- + 5000 +(1 row) + +-- +-- Error cases +-- +-- row pattern definition variable name must not appear more than once +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price), + UP AS price > PREV(price) +); +ERROR: row pattern definition variable name "up" appears more than once in DEFINE clause +LINE 11: UP AS price > PREV(price), + ^ +-- subqueries in DEFINE clause are not supported +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START LOWPRICE) + DEFINE + START AS TRUE, + LOWPRICE AS price < (SELECT 100) +); +ERROR: cannot use subquery in DEFINE expression +LINE 11: LOWPRICE AS price < (SELECT 100) + ^ +-- aggregates in DEFINE clause are not supported +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START LOWPRICE) + DEFINE + START AS TRUE, + LOWPRICE AS price < count(*) +); +ERROR: aggregate functions are not allowed in DEFINE +LINE 11: LOWPRICE AS price < count(*) + ^ +-- FRAME must start at current row when row patttern recognition is used +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); +ERROR: FRAME must start at current row when row patttern recognition is used +-- SEEK is not supported +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP TO NEXT ROW + SEEK + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); +ERROR: SEEK is not supported +LINE 8: SEEK + ^ +HINT: Use INITIAL. +-- PREV's argument must have at least 1 column reference +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP TO NEXT ROW + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(1), + DOWN AS price < PREV(1) +); +ERROR: row pattern navigation operation's argument must include at least one column reference diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule index 81e4222d26..35df8f159e 100644 --- a/src/test/regress/parallel_schedule +++ b/src/test/regress/parallel_schedule @@ -98,7 +98,7 @@ test: publication subscription # Another group of parallel tests # select_views depends on create_view # ---------- -test: select_views portals_p2 foreign_key cluster dependency guc bitmapops combocid tsearch tsdicts foreign_data window xmlmap functional_deps advisory_lock indirect_toast equivclass +test: select_views portals_p2 foreign_key cluster dependency guc bitmapops combocid tsearch tsdicts foreign_data window xmlmap functional_deps advisory_lock indirect_toast equivclass rpr # ---------- # Another group of parallel tests (JSON related) diff --git a/src/test/regress/sql/rpr.sql b/src/test/regress/sql/rpr.sql new file mode 100644 index 0000000000..a46abe6f0f --- /dev/null +++ b/src/test/regress/sql/rpr.sql @@ -0,0 +1,467 @@ +-- +-- Test for row pattern definition clause +-- + +CREATE TEMP TABLE stock ( + company TEXT, + tdate DATE, + price INTEGER +); +INSERT INTO stock VALUES ('company1', '2023-07-01', 100); +INSERT INTO stock VALUES ('company1', '2023-07-02', 200); +INSERT INTO stock VALUES ('company1', '2023-07-03', 150); +INSERT INTO stock VALUES ('company1', '2023-07-04', 140); +INSERT INTO stock VALUES ('company1', '2023-07-05', 150); +INSERT INTO stock VALUES ('company1', '2023-07-06', 90); +INSERT INTO stock VALUES ('company1', '2023-07-07', 110); +INSERT INTO stock VALUES ('company1', '2023-07-08', 130); +INSERT INTO stock VALUES ('company1', '2023-07-09', 120); +INSERT INTO stock VALUES ('company1', '2023-07-10', 130); +INSERT INTO stock VALUES ('company2', '2023-07-01', 50); +INSERT INTO stock VALUES ('company2', '2023-07-02', 2000); +INSERT INTO stock VALUES ('company2', '2023-07-03', 1500); +INSERT INTO stock VALUES ('company2', '2023-07-04', 1400); +INSERT INTO stock VALUES ('company2', '2023-07-05', 1500); +INSERT INTO stock VALUES ('company2', '2023-07-06', 60); +INSERT INTO stock VALUES ('company2', '2023-07-07', 1100); +INSERT INTO stock VALUES ('company2', '2023-07-08', 1300); +INSERT INTO stock VALUES ('company2', '2023-07-09', 1200); +INSERT INTO stock VALUES ('company2', '2023-07-10', 1300); + +SELECT * FROM stock; + +-- basic test using PREV +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w, + nth_value(tdate, 2) OVER w AS nth_second + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + +-- basic test using PREV. UP appears twice +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w, + nth_value(tdate, 2) OVER w AS nth_second + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+ UP+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + +-- basic test using PREV. Use '*' +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w, + nth_value(tdate, 2) OVER w AS nth_second + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP* DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + +-- basic test with none greedy pattern +SELECT company, tdate, price, count(*) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (A A A) + DEFINE + A AS price >= 140 AND price <= 150 +); + +-- last_value() should remain consistent +SELECT company, tdate, price, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + +-- omit "START" in DEFINE but it is ok because "START AS TRUE" is +-- implicitly defined. per spec. +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w, + nth_value(tdate, 2) OVER w AS nth_second + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + +-- the first row start with less than or equal to 100 +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (LOWPRICE UP+ DOWN+) + DEFINE + LOWPRICE AS price <= 100, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + +-- second row raises 120% +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (LOWPRICE UP+ DOWN+) + DEFINE + LOWPRICE AS price <= 100, + UP AS price > PREV(price) * 1.2, + DOWN AS price < PREV(price) +); + +-- using NEXT +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UPDOWN) + DEFINE + START AS TRUE, + UPDOWN AS price > PREV(price) AND price > NEXT(price) +); + +-- using AFTER MATCH SKIP TO NEXT ROW +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP TO NEXT ROW + INITIAL + PATTERN (START UPDOWN) + DEFINE + START AS TRUE, + UPDOWN AS price > PREV(price) AND price > NEXT(price) +); + +-- match everything + +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP PAST LAST ROW + INITIAL + PATTERN (A+) + DEFINE + A AS TRUE +); + +-- backtracking with reclassification of rows +-- using AFTER MATCH SKIP PAST LAST ROW +SELECT company, tdate, price, first_value(tdate) OVER w, last_value(tdate) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP PAST LAST ROW + INITIAL + PATTERN (A+ B+) + DEFINE + A AS price > 100, + B AS price > 100 +); + +-- backtracking with reclassification of rows +-- using AFTER MATCH SKIP TO NEXT ROW +SELECT company, tdate, price, first_value(tdate) OVER w, last_value(tdate) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP TO NEXT ROW + INITIAL + PATTERN (A+ B+) + DEFINE + A AS price > 100, + B AS price > 100 +); + +-- ROWS BETWEEN CURRENT ROW AND offset FOLLOWING +SELECT company, tdate, price, first_value(tdate) OVER w, last_value(tdate) OVER w, + count(*) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING + AFTER MATCH SKIP PAST LAST ROW + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + +-- +-- Aggregates +-- + +-- using AFTER MATCH SKIP PAST LAST ROW +SELECT company, tdate, price, + first_value(price) OVER w, + last_value(price) OVER w, + max(price) OVER w, + min(price) OVER w, + sum(price) OVER w, + avg(price) OVER w, + count(price) OVER w +FROM stock +WINDOW w AS ( +PARTITION BY company +ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING +AFTER MATCH SKIP PAST LAST ROW +INITIAL +PATTERN (START UP+ DOWN+) +DEFINE +START AS TRUE, +UP AS price > PREV(price), +DOWN AS price < PREV(price) +); + +-- using AFTER MATCH SKIP TO NEXT ROW +SELECT company, tdate, price, + first_value(price) OVER w, + last_value(price) OVER w, + max(price) OVER w, + min(price) OVER w, + sum(price) OVER w, + avg(price) OVER w, + count(price) OVER w +FROM stock +WINDOW w AS ( +PARTITION BY company +ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING +AFTER MATCH SKIP TO NEXT ROW +INITIAL +PATTERN (START UP+ DOWN+) +DEFINE +START AS TRUE, +UP AS price > PREV(price), +DOWN AS price < PREV(price) +); + +-- JOIN case +CREATE TEMP TABLE t1 (i int, v1 int); +CREATE TEMP TABLE t2 (j int, v2 int); +INSERT INTO t1 VALUES(1,10); +INSERT INTO t1 VALUES(1,11); +INSERT INTO t1 VALUES(1,12); +INSERT INTO t2 VALUES(2,10); +INSERT INTO t2 VALUES(2,11); +INSERT INTO t2 VALUES(2,12); + +SELECT * FROM t1, t2 WHERE t1.v1 <= 11 AND t2.v2 <= 11; + +SELECT *, count(*) OVER w FROM t1, t2 +WINDOW w AS ( + PARTITION BY t1.i + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (A) + DEFINE + A AS v1 <= 11 AND v2 <= 11 +); + +-- WITH case +WITH wstock AS ( + SELECT * FROM stock WHERE tdate < '2023-07-08' +) +SELECT tdate, price, +first_value(tdate) OVER w, +count(*) OVER w + FROM wstock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + +-- PREV has multiple column reference +CREATE TEMP TABLE rpr1 (id INTEGER, i SERIAL, j INTEGER); +INSERT INTO rpr1(id, j) SELECT 1, g*2 FROM generate_series(1, 10) AS g; +SELECT id, i, j, count(*) OVER w + FROM rpr1 + WINDOW w AS ( + PARTITION BY id + ORDER BY i + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP PAST LAST ROW + INITIAL + PATTERN (START COND+) + DEFINE + START AS TRUE, + COND AS PREV(i + j + 1) < 10 +); + +-- Smoke test for larger partitions. +WITH s AS ( + SELECT v, count(*) OVER w AS c + FROM (SELECT generate_series(1, 5000) v) + WINDOW w AS ( + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP PAST LAST ROW + INITIAL + PATTERN ( r+ ) + DEFINE r AS TRUE + ) +) +-- Should be exactly one long match across all rows. +SELECT * FROM s WHERE c > 0; + +WITH s AS ( + SELECT v, count(*) OVER w AS c + FROM (SELECT generate_series(1, 5000) v) + WINDOW w AS ( + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP PAST LAST ROW + INITIAL + PATTERN ( r ) + DEFINE r AS TRUE + ) +) +-- Every row should be its own match. +SELECT count(*) FROM s WHERE c > 0; + +-- +-- Error cases +-- + +-- row pattern definition variable name must not appear more than once +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price), + UP AS price > PREV(price) +); + +-- subqueries in DEFINE clause are not supported +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START LOWPRICE) + DEFINE + START AS TRUE, + LOWPRICE AS price < (SELECT 100) +); + +-- aggregates in DEFINE clause are not supported +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START LOWPRICE) + DEFINE + START AS TRUE, + LOWPRICE AS price < count(*) +); + +-- FRAME must start at current row when row patttern recognition is used +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + +-- SEEK is not supported +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP TO NEXT ROW + SEEK + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(price), + DOWN AS price < PREV(price) +); + +-- PREV's argument must have at least 1 column reference +SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w + FROM stock + WINDOW w AS ( + PARTITION BY company + ORDER BY tdate + ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + AFTER MATCH SKIP TO NEXT ROW + INITIAL + PATTERN (START UP+ DOWN+) + DEFINE + START AS TRUE, + UP AS price > PREV(1), + DOWN AS price < PREV(1) +); -- 2.25.1 ----Next_Part(Fri_Oct_25_13_04_53_2024_648)-- Content-Type: Text/X-Patch; charset=us-ascii Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="v23-0008-Allow-to-print-raw-parse-tree.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-04 04:47 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: --- src/backend/commands/user.c | 246 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 191 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..6d8e2fa8813 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,92 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --xlWYagR37YwJXkF8-- ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --fotX2lJRknAHpfH+ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Surya Poondla <[email protected]> Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --Dvg/WemKV0I3T/Od Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() @ 2026-07-06 08:28 Bertrand Drouvot <[email protected]> 0 siblings, 0 replies; 165+ messages in thread From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw) DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot <[email protected]> Reviewed-by: Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg --- src/backend/commands/user.c | 248 ++++++++++++++++++++++++++---------- src/include/commands/user.h | 9 ++ 2 files changed, 193 insertions(+), 64 deletions(-) 95.5% src/backend/commands/ 4.4% src/include/commands/ diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c index be11c49f919..5b869e91c17 100644 --- a/src/backend/commands/user.c +++ b/src/backend/commands/user.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "storage/lmgr.h" +#include "storage/sinval.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/catcache.h" @@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist, bool revoke_admin_option_only, DropBehavior behavior); static void InitGrantRoleOptions(GrantRoleOptions *popt); +static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); +static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); /* Check if current user has createrole privileges */ @@ -126,6 +131,94 @@ have_createrole_privilege(void) } +/* + * RoleNameGetOid + * Given a role name, look up its OID, lock it, and return the OID. + * + * This follows the same pattern as RangeVarGetRelidExtended(): + * name resolution, permission check (via callback), and lock acquisition are + * performed inside a retry loop. If invalidation messages arrive during the + * process (indicating concurrent DDL), we retry to ensure the name still + * resolves to the same OID. + * + * The callback is invoked before locking, giving callers a chance to check + * permissions. It receives the current rolename, the resolved OID, the + * previous OID (InvalidOid on first iteration), and a caller-supplied arg. + * If the callback raises an error, the function aborts without locking. + * + * If missing_ok is true and the role does not exist, returns InvalidOid. + * Otherwise, raises an error. + */ +Oid +RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok, + RoleNameGetOidCallback callback, void *callback_arg) +{ + uint64 inval_count; + Oid roleid; + Oid oldroleid = InvalidOid; + bool retry = false; + + for (;;) + { + /* + * Remember the current invalidation count so we can detect concurrent + * DDL after locking. + */ + inval_count = SharedInvalidMessageCounter; + + /* Look up the role name */ + roleid = get_role_oid(rolename, true); + + if (!OidIsValid(roleid)) + { + if (retry) + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + if (!missing_ok) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + return InvalidOid; + } + + /* + * Invoke caller-supplied callback before locking. This is a good + * place to check permissions: we haven't taken the lock yet, but we + * know the OID we intend to lock. If concurrent DDL changes things, + * the callback will be invoked again on the next iteration. + */ + if (callback) + callback(rolename, roleid, oldroleid, callback_arg); + + /* + * If upon retry we get back the same OID, the invalidation messages + * did not change the final answer. So we're done. + * + * If we got a different OID, we've locked the role that used to have + * this name rather than the one that does now. Release the old lock. + */ + if (retry) + { + if (roleid == oldroleid) + break; + UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode); + } + + /* Lock the role */ + LockSharedObject(AuthIdRelationId, roleid, 0, lockmode); + + /* If no invalidation messages were processed, we're done */ + if (inval_count == SharedInvalidMessageCounter) + break; + + /* Something may have changed, retry */ + retry = true; + oldroleid = roleid; + } + + return roleid; +} + + /* * CREATE ROLE */ @@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt) } +/* + * Before acquiring a role lock for DROP ROLE, check that the role is not the + * current/session user and that the caller has sufficient privileges to drop it. + */ +static void +RoleNameCallbackForDropRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + HeapTuple tuple; + Form_pg_authid roleform; + + if (roleid == GetUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetOuterUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("current user cannot be dropped"))); + if (roleid == GetSessionUserId()) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_IN_USE), + errmsg("session user cannot be dropped"))); + + tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid)); + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("role \"%s\" does not exist", rolename))); + + roleform = (Form_pg_authid) GETSTRUCT(tuple); + + /* + * For safety's sake, we allow createrole holders to drop ordinary roles + * but not superuser roles, and only if they also have ADMIN OPTION. + */ + if (roleform->rolsuper && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", + "SUPERUSER", "SUPERUSER"))); + if (!is_admin_of_role(GetUserId(), roleid)) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("permission denied to drop role"), + errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", + "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); + + ReleaseSysCache(tuple); +} + + /* * DROP ROLE */ @@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt) { RoleSpec *rolspec = lfirst(item); char *role; - HeapTuple tuple, - tmp_tuple; - Form_pg_authid roleform; + HeapTuple tmp_tuple; ScanKeyData scankey; SysScanDesc sscan; Oid roleid; @@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt) errmsg("cannot use special role specifier in DROP ROLE"))); role = rolspec->rolename; - tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role)); - if (!HeapTupleIsValid(tuple)) - { - if (!stmt->missing_ok) - { - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("role \"%s\" does not exist", role))); - } - else - { - ereport(NOTICE, - (errmsg("role \"%s\" does not exist, skipping", - role))); - } + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP or ALTER commits between name + * resolution and lock acquisition. + */ + roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok, + RoleNameCallbackForDropRole, NULL); + if (!OidIsValid(roleid)) + { + /* missing_ok case: role doesn't exist */ + ereport(NOTICE, + (errmsg("role \"%s\" does not exist, skipping", + role))); continue; } - roleform = (Form_pg_authid) GETSTRUCT(tuple); - roleid = roleform->oid; - - if (roleid == GetUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetOuterUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("current user cannot be dropped"))); - if (roleid == GetSessionUserId()) - ereport(ERROR, - (errcode(ERRCODE_OBJECT_IN_USE), - errmsg("session user cannot be dropped"))); - - /* - * For safety's sake, we allow createrole holders to drop ordinary - * roles but not superuser roles, and only if they also have ADMIN - * OPTION. - */ - if (roleform->rolsuper && !superuser()) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute may drop roles with the %s attribute.", - "SUPERUSER", "SUPERUSER"))); - if (!is_admin_of_role(GetUserId(), roleid)) - ereport(ERROR, - (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), - errmsg("permission denied to drop role"), - errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.", - "CREATEROLE", "ADMIN", NameStr(roleform->rolname)))); - /* DROP hook for the role being removed */ InvokeObjectDropHook(AuthIdRelationId, roleid, 0); - /* Don't leak the syscache tuple */ - ReleaseSysCache(tuple); - - /* - * Lock the role, so nobody can add dependencies to her while we drop - * her. We keep the lock until the end of transaction. - */ - LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock); - /* * If there is a pg_auth_members entry that has one of the roles to be * dropped as the roleid or member, it should be silently removed, but @@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname) return address; } +/* + * Before acquiring a role lock for GRANT/REVOKE, check that the current user + * has authorization to grant/revoke membership in the specified role. + */ +static void +RoleNameCallbackForGrantRole(const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg) +{ + bool is_grant = *((bool *) callback_arg); + Oid currentUserId = GetUserId(); + + check_role_membership_authorization(currentUserId, roleid, is_grant); +} + + /* * GrantRoleStmt * @@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt) (errcode(ERRCODE_INVALID_GRANT_OPERATION), errmsg("column names cannot be included in GRANT/REVOKE ROLE"))); - roleid = get_role_oid(rolename, false); - check_role_membership_authorization(currentUserId, - roleid, stmt->is_grant); + /* + * Use RoleNameGetOid to resolve the name, check permissions, and lock + * the role atomically with a retry loop. This prevents race + * conditions where a concurrent DROP commits between name resolution + * and lock acquisition. + */ + roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false, + RoleNameCallbackForGrantRole, &stmt->is_grant); if (stmt->is_grant) AddRoleMems(currentUserId, rolename, roleid, stmt->grantee_roles, grantee_ids, diff --git a/src/include/commands/user.h b/src/include/commands/user.h index 97dcb93791b..17263452250 100644 --- a/src/include/commands/user.h +++ b/src/include/commands/user.h @@ -21,6 +21,15 @@ extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */ extern PGDLLIMPORT char *createrole_self_grant; +/* Callback for RoleNameGetOid, invoked after name resolution but before locking */ +typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid, + Oid oldroleid, void *callback_arg); + +extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode, + bool missing_ok, + RoleNameGetOidCallback callback, + void *callback_arg); + /* Hook to check passwords in CreateRole() and AlterRole() */ typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null); -- 2.34.1 --cOHldBwZEf1OqVbN Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch" ^ permalink raw reply [nested|flat] 165+ messages in thread
end of thread, other threads:[~2026-07-06 08:28 UTC | newest] Thread overview: 165+ messages (download: mbox mbox.gz follow: Atom feed) -- links below jump to the message on this page -- 2024-10-25 03:56 [PATCH v23 7/8] Row pattern recognition patch (tests). Tatsuo Ishii <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]> 2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
This inbox is served by agora; see mirroring instructions for how to clone and mirror all data and code used for this inbox