agora inbox for [email protected]  
help / color / mirror / Atom feed
[PATCH v3 2/2] Try to avoid a rewrite when adding a stored generated column
205+ messages / 2 participants
[nested] [flat]

* [PATCH v3 2/2] Try to avoid a rewrite when adding a stored generated column
@ 2026-04-24 08:44 Alberto Piai <[email protected]>
  0 siblings, 0 replies; 205+ messages in thread

From: Alberto Piai @ 2026-04-24 08:44 UTC (permalink / raw)

This builds upon basic support for

... ALTER COLUMN ... ADD GENERATED ALWAYS AS (expr) STORED

If we can find a constraint which proves that the given column is
already always equal to the new generated column expression, skip the
expensive rewrite of the table.

The check constraint must use an equality operator which is mergejoinable, and
the expression must match exactly the generated column's default
expression.
---
 src/backend/catalog/pg_constraint.c       |  75 +++++++
 src/backend/commands/tablecmds.c          |  46 +++--
 src/include/catalog/pg_constraint.h       |   2 +
 src/test/regress/expected/alter_table.out | 232 +++++++++++++++++++++-
 src/test/regress/sql/alter_table.sql      | 147 ++++++++++++++
 5 files changed, 481 insertions(+), 21 deletions(-)

diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
index b12765ae691..cfb0a0068cf 100644
--- a/src/backend/catalog/pg_constraint.c
+++ b/src/backend/catalog/pg_constraint.c
@@ -17,6 +17,7 @@
 #include "access/genam.h"
 #include "access/gist.h"
 #include "access/htup_details.h"
+#include "access/relation.h"
 #include "access/sysattr.h"
 #include "access/table.h"
 #include "catalog/catalog.h"
@@ -29,6 +30,8 @@
 #include "catalog/pg_type.h"
 #include "commands/defrem.h"
 #include "common/int.h"
+#include "nodes/nodeFuncs.h"
+#include "parser/parse_relation.h"
 #include "utils/array.h"
 #include "utils/builtins.h"
 #include "utils/fmgroids.h"
@@ -694,6 +697,78 @@ findDomainNotNullConstraint(Oid typid)
 	return retval;
 }
 
+/*
+ * Given a relation, an attnum and a (cooked) expression, this returns true if
+ * it finds a CHECK constraint which proves that the given column is equal to
+ * the expression.
+ *
+ * The constraint must use a mergejoinable operator for the type of the column,
+ * a concept used by the planner as well to infer equivalence classes on the
+ * terms in a query (see op_mergejoinable()).
+ *
+ * The expressions are compared structurally, so they must match exactly for
+ * this check to succeed.
+ */
+bool
+findStructuralCheckConstraintOnAttr(Oid relid, AttrNumber attnum,
+									const Node *target_expr)
+{
+	Relation	pg_constraint;
+	HeapTuple	conTup;
+	SysScanDesc scan;
+	ScanKeyData key;
+	bool		found = false;
+
+	pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
+	ScanKeyInit(&key,
+				Anum_pg_constraint_conrelid,
+				BTEqualStrategyNumber, F_OIDEQ,
+				ObjectIdGetDatum(relid));
+	scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId,
+							  true, NULL, 1, &key);
+
+	while (HeapTupleIsValid(conTup = systable_getnext(scan)))
+	{
+		Form_pg_constraint con = GETSTRUCT(conTup);
+		char	   *conbin;
+		Datum		val;
+		Node	   *conexpr;
+
+		if (con->contype != CONSTRAINT_CHECK)
+			continue;
+		if (!con->convalidated)
+			continue;
+
+		val = SysCacheGetAttrNotNull(CONSTROID, conTup,
+									 Anum_pg_constraint_conbin);
+		conbin = TextDatumGetCString(val);
+		conexpr = stringToNode(conbin);
+
+		if (IsA(conexpr, OpExpr))
+		{
+			OpExpr	   *op = (OpExpr *) conexpr;
+
+			if (list_length(op->args) == 2 && IsA(linitial(op->args), Var))
+			{
+				Var		   *var = linitial(op->args);
+
+				if (var->varattno == attnum &&
+					op_mergejoinable(op->opno, exprType((Node *) var)) &&
+					equal(lsecond(op->args), target_expr))
+				{
+					found = true;
+					break;
+				}
+			}
+		}
+	}
+
+	systable_endscan(scan);
+	table_close(pg_constraint, AccessShareLock);
+
+	return found;
+}
+
 /*
  * Given a pg_constraint tuple for a not-null constraint, return the column
  * number it is for.
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index aa54c629f8b..c886e6e5ca7 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -8938,6 +8938,7 @@ ATExecAddGeneratedAsExprStored(AlteredTableInfo *tab,
 	NewColumnValue *newval;
 	RawColumnDefault *rawEnt;
 	Relation	pg_attribute;
+	bool		rewrite;
 
 	Assert(def->raw_expr != NULL);
 	Assert(def->cooked_expr == NULL);
@@ -9001,29 +9002,36 @@ ATExecAddGeneratedAsExprStored(AlteredTableInfo *tab,
 	/* Make above changes visible */
 	CommandCounterIncrement();
 
-	/*
-	 * Clear all the missing values if we're rewriting the table, since this
-	 * renders them pointless.
-	 */
-	RelationClearMissing(rel);
-
-	/* Make above changes visible */
-	CommandCounterIncrement();
-
-	/* Drop any pg_statistic entry for the column */
-	RemoveStatistics(RelationGetRelid(rel), attnum);
-
 	/* Build a concrete expression for the new default (generated) value */
 	defval = (Expr *) build_column_default(rel, attnum);
 	defval = expression_planner(defval);
 
-	/* Schedule a rewrite */
-	newval = palloc0_object(NewColumnValue);
-	newval->attnum = attnum;
-	newval->expr = defval;
-	newval->is_generated = true;
-	tab->newvals = lappend(tab->newvals, newval);
-	tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
+	rewrite = !findStructuralCheckConstraintOnAttr(RelationGetRelid(rel),
+												   attnum,
+												   (Node *) defval);
+
+	if (rewrite)
+	{
+		/*
+		 * Clear all the missing values if we're rewriting the table, since
+		 * this renders them pointless.
+		 */
+		RelationClearMissing(rel);
+
+		/* Make above changes visible */
+		CommandCounterIncrement();
+
+		/* Drop any pg_statistic entry for the column */
+		RemoveStatistics(RelationGetRelid(rel), attnum);
+
+		/* Schedule a rewrite */
+		newval = palloc0_object(NewColumnValue);
+		newval->attnum = attnum;
+		newval->expr = defval;
+		newval->is_generated = true;
+		tab->newvals = lappend(tab->newvals, newval);
+		tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
+	}
 
 	InvokeObjectPostAlterHook(RelationRelationId,
 							  RelationGetRelid(rel), attnum);
diff --git a/src/include/catalog/pg_constraint.h b/src/include/catalog/pg_constraint.h
index 1b7fedf1750..7ac9e00c28b 100644
--- a/src/include/catalog/pg_constraint.h
+++ b/src/include/catalog/pg_constraint.h
@@ -266,6 +266,8 @@ extern char *ChooseConstraintName(const char *name1, const char *name2,
 extern HeapTuple findNotNullConstraintAttnum(Oid relid, AttrNumber attnum);
 extern HeapTuple findNotNullConstraint(Oid relid, const char *colname);
 extern HeapTuple findDomainNotNullConstraint(Oid typid);
+extern bool findStructuralCheckConstraintOnAttr(Oid relid, AttrNumber attnum,
+												const Node *target_expr);
 extern AttrNumber extractNotNullColumn(HeapTuple constrTup);
 extern bool AdjustNotNullInheritance(Oid relid, AttrNumber attnum, const char *new_conname,
 									 bool is_local, bool is_no_inherit, bool is_notvalid);
diff --git a/src/test/regress/expected/alter_table.out b/src/test/regress/expected/alter_table.out
index 08981f4e380..5346791fd8d 100644
--- a/src/test/regress/expected/alter_table.out
+++ b/src/test/regress/expected/alter_table.out
@@ -4955,6 +4955,233 @@ select :idx_filenode_before != :idx_filenode_after as did_rewrite_idx;
  t
 (1 row)
 
+drop table testgen.t3;
+-- turning a regular column into a stored generated column
+-- without rewriting the table (when a check constraint proves it isn't needed)
+create table testgen.t4 (a int, b int not null);
+insert into testgen.t4 (a, b) select x, x * 2 from generate_series(0, 5) x;
+alter table testgen.t4 add constraint chk_gen_clause check (b = a * 2);
+select pg_relation_filenode('testgen.t4') as t4_filenode_before \gset
+alter table testgen.t4 alter column b add generated always as (a * 2) stored;
+select pg_relation_filenode('testgen.t4') as t4_filenode_after \gset
+select :t4_filenode_before = :t4_filenode_after as did_skip_rewrite;
+ did_skip_rewrite 
+------------------
+ t
+(1 row)
+
+\d+ testgen.t4
+                                                 Table "testgen.t4"
+ Column |  Type   | Collation | Nullable |              Default               | Storage | Stats target | Description 
+--------+---------+-----------+----------+------------------------------------+---------+--------------+-------------
+ a      | integer |           |          |                                    | plain   |              | 
+ b      | integer |           | not null | generated always as (a * 2) stored | plain   |              | 
+Check constraints:
+    "chk_gen_clause" CHECK (b = (a * 2))
+Not-null constraints:
+    "t4_b_not_null" NOT NULL "b"
+
+drop table testgen.t4;
+-- turning a regular column into a stored generated column
+-- same as the previous case, but a rewrite happens since the constraint is not
+-- valid
+create table testgen.t4 (a int, b int not null);
+insert into testgen.t4 (a, b) select x, x * 2 from generate_series(0, 5) x;
+alter table testgen.t4 add constraint chk_gen_clause check (b = a * 2) not valid;
+select pg_relation_filenode('testgen.t4') as t4_filenode_before \gset
+alter table testgen.t4 alter column b add generated always as (a * 2) stored;
+select pg_relation_filenode('testgen.t4') as t4_filenode_after \gset
+select :t4_filenode_before != :t4_filenode_after as did_rewrite;
+ did_rewrite 
+-------------
+ t
+(1 row)
+
+\d+ testgen.t4
+                                                 Table "testgen.t4"
+ Column |  Type   | Collation | Nullable |              Default               | Storage | Stats target | Description 
+--------+---------+-----------+----------+------------------------------------+---------+--------------+-------------
+ a      | integer |           |          |                                    | plain   |              | 
+ b      | integer |           | not null | generated always as (a * 2) stored | plain   |              | 
+Check constraints:
+    "chk_gen_clause" CHECK (b = (a * 2)) NOT VALID
+Not-null constraints:
+    "t4_b_not_null" NOT NULL "b"
+
+drop table testgen.t4;
+-- turning a regular column into a stored generated column
+-- same as the previous case, but a rewrite happens since the constraint
+-- operator is not mergejoinable
+create table testgen.t4 (a int, b int not null);
+insert into testgen.t4 (a, b) select x, x * 2 from generate_series(0, 5) x;
+alter table testgen.t4 add constraint chk_gen_clause check (b >= a * 2);
+select pg_relation_filenode('testgen.t4') as t4_filenode_before \gset
+alter table testgen.t4 alter column b add generated always as (a * 3) stored;
+select pg_relation_filenode('testgen.t4') as t4_filenode_after \gset
+select :t4_filenode_before != :t4_filenode_after as did_rewrite;
+ did_rewrite 
+-------------
+ t
+(1 row)
+
+\d+ testgen.t4
+                                                 Table "testgen.t4"
+ Column |  Type   | Collation | Nullable |              Default               | Storage | Stats target | Description 
+--------+---------+-----------+----------+------------------------------------+---------+--------------+-------------
+ a      | integer |           |          |                                    | plain   |              | 
+ b      | integer |           | not null | generated always as (a * 3) stored | plain   |              | 
+Check constraints:
+    "chk_gen_clause" CHECK (b >= (a * 2))
+Not-null constraints:
+    "t4_b_not_null" NOT NULL "b"
+
+drop table testgen.t4;
+-- test the whole process for adding a stored generated column without
+-- long-lived exclusive locks
+create table testgen.t5 (a int);
+select pg_relation_filenode('testgen.t5') as t5_filenode_before \gset
+insert into testgen.t5 select x from generate_series(1, 5) x;
+alter table testgen.t5 add column b int;
+-- take care of new and updated columns
+create function testgen.gen () returns trigger language plpgsql as $$
+begin
+  new.b = new.a * 2; return new;
+end
+$$;
+create trigger testgen_gen
+    before insert or update on testgen.t5
+    for each row execute function testgen.gen();
+-- add the constraint as not valid: enforced only for new and updated rows
+begin;
+alter table testgen.t5
+    add constraint chk_gen_clause check (b = a * 2) not valid;
+select locktype, mode from pg_locks
+  where relation = 'testgen.t5'::regclass and granted;
+ locktype |        mode         
+----------+---------------------
+ relation | AccessExclusiveLock
+(1 row)
+
+commit;
+insert into testgen.t5 (a) values (100), (200), (300);
+-- backfill existing rows at the appropriate pace
+update testgen.t5 set b = a * 2 where b is null;
+-- validate: this scans the table, but without an exclusive lock
+begin;
+alter table testgen.t5 validate constraint chk_gen_clause;
+select locktype, mode from pg_locks
+  where relation = 'testgen.t5'::regclass and granted;
+ locktype |           mode           
+----------+--------------------------
+ relation | ShareUpdateExclusiveLock
+(1 row)
+
+commit;
+-- now the schema update, which skips the rewrite because of the check
+begin;
+drop trigger testgen_gen on testgen.t5;
+alter table testgen.t5 alter column b
+    add generated always as (a * 2) stored;
+select locktype, mode from pg_locks
+where relation = 'testgen.t5'::regclass and granted;
+ locktype |        mode         
+----------+---------------------
+ relation | AccessShareLock
+ relation | AccessExclusiveLock
+(2 rows)
+
+commit;
+select pg_relation_filenode('testgen.t5') as t5_filenode_after \gset
+select :t5_filenode_before = :t5_filenode_after as did_skip_rewrite;
+ did_skip_rewrite 
+------------------
+ t
+(1 row)
+
+\d+ testgen.t5
+                                                 Table "testgen.t5"
+ Column |  Type   | Collation | Nullable |              Default               | Storage | Stats target | Description 
+--------+---------+-----------+----------+------------------------------------+---------+--------------+-------------
+ a      | integer |           |          |                                    | plain   |              | 
+ b      | integer |           |          | generated always as (a * 2) stored | plain   |              | 
+Check constraints:
+    "chk_gen_clause" CHECK (b = (a * 2))
+
+-- test support for partitioned tables and inheritance
+create table testgen.tpart (a int, b int) partition by hash (a);
+create table testgen.tpart_p1 partition of testgen.tpart
+  for values with (modulus 2, remainder 0);
+create table testgen.tpart_p2 partition of testgen.tpart
+  for values with (modulus 2, remainder 1);
+insert into testgen.tpart (a, b) select x, x from generate_series(1, 5) x;
+-- altering the parent table, recursing
+begin;
+alter table testgen.tpart alter column b
+  add generated always as (a * 2) stored;
+-- expected: all the partitions have been rewritten
+select a, b, a * 2 as expected, b = (a * 2) as correct
+  from testgen.tpart_p1 order by a;
+ a | b | expected | correct 
+---+---+----------+---------
+ 1 | 2 |        2 | t
+ 2 | 4 |        4 | t
+(2 rows)
+
+select a, b, a * 2 as expected, b = (a * 2) as correct
+  from testgen.tpart_p2 order by a;
+ a | b  | expected | correct 
+---+----+----------+---------
+ 3 |  6 |        6 | t
+ 4 |  8 |        8 | t
+ 5 | 10 |       10 | t
+(3 rows)
+
+rollback;
+-- altering a single partition is not allowed
+begin;
+-- expected: error
+alter table testgen.tpart_p1 alter column b
+    add generated always as (a * 2) stored;
+ERROR:  cannot change inherited column to be a stored generated column
+rollback;
+-- altering only the parent table is not allowed
+begin;
+-- expected: error
+alter table only testgen.tpart alter column b
+    add generated always as (a * 2) stored;
+ERROR:  ALTER TABLE / ADD GENERATED ALWAYS AS (expr) STORED must be applied to child tables too
+rollback;
+drop table testgen.tpart;
+-- subpartitions
+create table testgen.tpart (a int, b int, c int)
+  partition by hash (a);
+create table testgen.tpart_p1 partition of testgen.tpart
+  for values with (modulus 2, remainder 0)
+  partition by hash (b);
+create table testgen.tpart_p1_1 partition of testgen.tpart_p1
+  for values with (modulus 2, remainder 0);
+create table testgen.tpart_p1_2 partition of testgen.tpart_p1
+  for values with (modulus 2, remainder 1);
+create table testgen.tpart_p2 partition of testgen.tpart
+  for values with (modulus 2, remainder 1)
+  partition by hash (b);
+create table testgen.tpart_p2_1 partition of testgen.tpart_p2
+  for values with (modulus 2, remainder 0);
+create table testgen.tpart_p2_2 partition of testgen.tpart_p2
+  for values with (modulus 2, remainder 1);
+insert into testgen.tpart (a, b)
+  select x, y
+    from generate_series(1, 5) x
+    cross join generate_series(1, 5) y;
+-- currently, it is not possible to change the generated state of an
+-- inheritance tree of depth >= 2 (same as in DROP EXPRESSION), so we expect an
+-- error here. This might be fixed later.
+begin;
+alter table testgen.tpart alter column c
+    add generated always as (a + b) stored;
+ERROR:  ALTER TABLE / ADD GENERATED ALWAYS AS (expr) STORED must be applied to child tables too
+rollback;
+drop table testgen.tpart;
 -- tests for invalid invocations
 alter table doesnotexist alter column foo
   add generated always as (bar * 2) stored;
@@ -4998,6 +5225,7 @@ alter table testgen.t3 alter column b
 ERROR:  cannot use subquery in column generation expression
 drop table testgen.t3;
 drop schema testgen cascade;
-NOTICE:  drop cascades to 4 other objects
-DETAIL:  drop cascades to table testgen.t3
+NOTICE:  drop cascades to 3 other objects
+DETAIL:  drop cascades to table testgen.t5
+drop cascades to function testgen.gen()
 drop cascades to table testgen.t1
diff --git a/src/test/regress/sql/alter_table.sql b/src/test/regress/sql/alter_table.sql
index 76187083289..efb08b9ff70 100644
--- a/src/test/regress/sql/alter_table.sql
+++ b/src/test/regress/sql/alter_table.sql
@@ -3198,6 +3198,153 @@ select pg_relation_filenode('testgen.idx_b') as idx_filenode_after \gset
 select :idx_filenode_before != :idx_filenode_after as did_rewrite_idx;
 drop table testgen.t3;
 
+-- turning a regular column into a stored generated column
+-- without rewriting the table (when a check constraint proves it isn't needed)
+create table testgen.t4 (a int, b int not null);
+insert into testgen.t4 (a, b) select x, x * 2 from generate_series(0, 5) x;
+alter table testgen.t4 add constraint chk_gen_clause check (b = a * 2);
+select pg_relation_filenode('testgen.t4') as t4_filenode_before \gset
+alter table testgen.t4 alter column b add generated always as (a * 2) stored;
+select pg_relation_filenode('testgen.t4') as t4_filenode_after \gset
+select :t4_filenode_before = :t4_filenode_after as did_skip_rewrite;
+\d+ testgen.t4
+drop table testgen.t4;
+
+-- turning a regular column into a stored generated column
+-- same as the previous case, but a rewrite happens since the constraint is not
+-- valid
+create table testgen.t4 (a int, b int not null);
+insert into testgen.t4 (a, b) select x, x * 2 from generate_series(0, 5) x;
+alter table testgen.t4 add constraint chk_gen_clause check (b = a * 2) not valid;
+select pg_relation_filenode('testgen.t4') as t4_filenode_before \gset
+alter table testgen.t4 alter column b add generated always as (a * 2) stored;
+select pg_relation_filenode('testgen.t4') as t4_filenode_after \gset
+select :t4_filenode_before != :t4_filenode_after as did_rewrite;
+\d+ testgen.t4
+drop table testgen.t4;
+
+-- turning a regular column into a stored generated column
+-- same as the previous case, but a rewrite happens since the constraint
+-- operator is not mergejoinable
+create table testgen.t4 (a int, b int not null);
+insert into testgen.t4 (a, b) select x, x * 2 from generate_series(0, 5) x;
+alter table testgen.t4 add constraint chk_gen_clause check (b >= a * 2);
+select pg_relation_filenode('testgen.t4') as t4_filenode_before \gset
+alter table testgen.t4 alter column b add generated always as (a * 3) stored;
+select pg_relation_filenode('testgen.t4') as t4_filenode_after \gset
+select :t4_filenode_before != :t4_filenode_after as did_rewrite;
+\d+ testgen.t4
+drop table testgen.t4;
+
+-- test the whole process for adding a stored generated column without
+-- long-lived exclusive locks
+create table testgen.t5 (a int);
+select pg_relation_filenode('testgen.t5') as t5_filenode_before \gset
+insert into testgen.t5 select x from generate_series(1, 5) x;
+alter table testgen.t5 add column b int;
+-- take care of new and updated columns
+create function testgen.gen () returns trigger language plpgsql as $$
+begin
+  new.b = new.a * 2; return new;
+end
+$$;
+create trigger testgen_gen
+    before insert or update on testgen.t5
+    for each row execute function testgen.gen();
+-- add the constraint as not valid: enforced only for new and updated rows
+begin;
+alter table testgen.t5
+    add constraint chk_gen_clause check (b = a * 2) not valid;
+select locktype, mode from pg_locks
+  where relation = 'testgen.t5'::regclass and granted;
+commit;
+insert into testgen.t5 (a) values (100), (200), (300);
+-- backfill existing rows at the appropriate pace
+update testgen.t5 set b = a * 2 where b is null;
+-- validate: this scans the table, but without an exclusive lock
+begin;
+alter table testgen.t5 validate constraint chk_gen_clause;
+select locktype, mode from pg_locks
+  where relation = 'testgen.t5'::regclass and granted;
+commit;
+-- now the schema update, which skips the rewrite because of the check
+begin;
+drop trigger testgen_gen on testgen.t5;
+alter table testgen.t5 alter column b
+    add generated always as (a * 2) stored;
+select locktype, mode from pg_locks
+where relation = 'testgen.t5'::regclass and granted;
+commit;
+select pg_relation_filenode('testgen.t5') as t5_filenode_after \gset
+select :t5_filenode_before = :t5_filenode_after as did_skip_rewrite;
+\d+ testgen.t5
+
+-- test support for partitioned tables and inheritance
+create table testgen.tpart (a int, b int) partition by hash (a);
+create table testgen.tpart_p1 partition of testgen.tpart
+  for values with (modulus 2, remainder 0);
+create table testgen.tpart_p2 partition of testgen.tpart
+  for values with (modulus 2, remainder 1);
+insert into testgen.tpart (a, b) select x, x from generate_series(1, 5) x;
+
+-- altering the parent table, recursing
+begin;
+alter table testgen.tpart alter column b
+  add generated always as (a * 2) stored;
+-- expected: all the partitions have been rewritten
+select a, b, a * 2 as expected, b = (a * 2) as correct
+  from testgen.tpart_p1 order by a;
+select a, b, a * 2 as expected, b = (a * 2) as correct
+  from testgen.tpart_p2 order by a;
+rollback;
+
+-- altering a single partition is not allowed
+begin;
+-- expected: error
+alter table testgen.tpart_p1 alter column b
+    add generated always as (a * 2) stored;
+rollback;
+
+-- altering only the parent table is not allowed
+begin;
+-- expected: error
+alter table only testgen.tpart alter column b
+    add generated always as (a * 2) stored;
+rollback;
+
+drop table testgen.tpart;
+
+-- subpartitions
+create table testgen.tpart (a int, b int, c int)
+  partition by hash (a);
+create table testgen.tpart_p1 partition of testgen.tpart
+  for values with (modulus 2, remainder 0)
+  partition by hash (b);
+create table testgen.tpart_p1_1 partition of testgen.tpart_p1
+  for values with (modulus 2, remainder 0);
+create table testgen.tpart_p1_2 partition of testgen.tpart_p1
+  for values with (modulus 2, remainder 1);
+create table testgen.tpart_p2 partition of testgen.tpart
+  for values with (modulus 2, remainder 1)
+  partition by hash (b);
+create table testgen.tpart_p2_1 partition of testgen.tpart_p2
+  for values with (modulus 2, remainder 0);
+create table testgen.tpart_p2_2 partition of testgen.tpart_p2
+  for values with (modulus 2, remainder 1);
+insert into testgen.tpart (a, b)
+  select x, y
+    from generate_series(1, 5) x
+    cross join generate_series(1, 5) y;
+-- currently, it is not possible to change the generated state of an
+-- inheritance tree of depth >= 2 (same as in DROP EXPRESSION), so we expect an
+-- error here. This might be fixed later.
+begin;
+alter table testgen.tpart alter column c
+    add generated always as (a + b) stored;
+rollback;
+
+drop table testgen.tpart;
+
 -- tests for invalid invocations
 alter table doesnotexist alter column foo
   add generated always as (bar * 2) stored;
-- 
2.47.0


--4wx636ozsu2eakgd--





^ permalink  raw  reply  [nested|flat] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ 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; 205+ 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] 205+ messages in thread


end of thread, other threads:[~2026-07-06 08:28 UTC | newest]

Thread overview: 205+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-04-24 08:44 [PATCH v3 2/2] Try to avoid a rewrite when adding a stored generated column Alberto Piai <[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-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 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 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 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]>
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 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 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 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 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 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 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 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 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 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 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 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]>
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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]>
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 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 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 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 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 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]>

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox