agora inbox for [email protected]  
help / color / mirror / Atom feed
[PATCH v44 01/10] Make index_concurrently_create_copy more general
153+ messages / 2 participants
[nested] [flat]

* [PATCH v44 01/10] Make index_concurrently_create_copy more general
@ 2026-03-24 18:02 Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 153+ messages in thread

From: Álvaro Herrera @ 2026-03-24 18:02 UTC (permalink / raw)

Add a 'boolean concurrent' option, and make it work for both cases.
Also rename it to index_create_copy.

This allows it to be reused for other purposes -- specifically, for
REPACK CONCURRENTLY.

With the CONCURRENTLY option, REPACK cannot simply swap the heap file and
rebuild its indexes. Instead, it needs to build a separate set of indexes
(including system catalog entries) *before* the actual swap, to reduce the
time AccessExclusiveLock needs to be held for.  This approach is
different from what CREATE INDEX CONCURRENTLY does.

Per a suggestion from Mihail Nikalayeu.

Author: Antonin Houska <[email protected]>
Discussion: https://postgr.es/m/41104.1754922120@localhost
---
 src/backend/catalog/index.c      | 39 +++++++++++++++++++-------------
 src/backend/commands/indexcmds.c | 15 +++++++-----
 src/backend/nodes/makefuncs.c    |  9 ++++----
 src/include/catalog/index.h      |  7 +++---
 src/include/nodes/makefuncs.h    |  4 +++-
 5 files changed, 43 insertions(+), 31 deletions(-)

diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c
index d8219b18c48..de7182a85a9 100644
--- a/src/backend/catalog/index.c
+++ b/src/backend/catalog/index.c
@@ -1289,17 +1289,17 @@ index_create(Relation heapRelation,
 }
 
 /*
- * index_concurrently_create_copy
+ * index_create_copy
  *
- * Create concurrently an index based on the definition of the one provided by
- * caller.  The index is inserted into catalogs and needs to be built later
- * on.  This is called during concurrent reindex processing.
+ * Create an index based on the definition of the one provided by caller.  The
+ * index is inserted into catalogs. If 'concurrently' is TRUE, it needs to be
+ * built later on; otherwise it's built immediately.
  *
  * "tablespaceOid" is the tablespace to use for this index.
  */
 Oid
-index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId,
-							   Oid tablespaceOid, const char *newName)
+index_create_copy(Relation heapRelation, bool concurrently,
+				  Oid oldIndexId, Oid tablespaceOid, const char *newName)
 {
 	Relation	indexRelation;
 	IndexInfo  *oldInfo,
@@ -1318,6 +1318,7 @@ index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId,
 	List	   *indexColNames = NIL;
 	List	   *indexExprs = NIL;
 	List	   *indexPreds = NIL;
+	int			flags = 0;
 
 	indexRelation = index_open(oldIndexId, RowExclusiveLock);
 
@@ -1328,7 +1329,7 @@ index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId,
 	 * Concurrent build of an index with exclusion constraints is not
 	 * supported.
 	 */
-	if (oldInfo->ii_ExclusionOps != NULL)
+	if (oldInfo->ii_ExclusionOps != NULL && concurrently)
 		ereport(ERROR,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("concurrent index creation for exclusion constraints is not supported")));
@@ -1384,9 +1385,7 @@ index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId,
 	}
 
 	/*
-	 * Build the index information for the new index.  Note that rebuild of
-	 * indexes with exclusion constraints is not supported, hence there is no
-	 * need to fill all the ii_Exclusion* fields.
+	 * Build the index information for the new index.
 	 */
 	newInfo = makeIndexInfo(oldInfo->ii_NumIndexAttrs,
 							oldInfo->ii_NumIndexKeyAttrs,
@@ -1395,10 +1394,13 @@ index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId,
 							indexPreds,
 							oldInfo->ii_Unique,
 							oldInfo->ii_NullsNotDistinct,
-							false,	/* not ready for inserts */
-							true,
+							!concurrently,	/* isready */
+							concurrently,	/* concurrent */
 							indexRelation->rd_indam->amsummarizing,
-							oldInfo->ii_WithoutOverlaps);
+							oldInfo->ii_WithoutOverlaps,
+							oldInfo->ii_ExclusionOps,
+							oldInfo->ii_ExclusionProcs,
+							oldInfo->ii_ExclusionStrats);
 
 	/*
 	 * Extract the list of column names and the column numbers for the new
@@ -1436,6 +1438,9 @@ index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId,
 		stattargets[i].isnull = isnull;
 	}
 
+	if (concurrently)
+		flags = INDEX_CREATE_SKIP_BUILD | INDEX_CREATE_CONCURRENT;
+
 	/*
 	 * Now create the new index.
 	 *
@@ -1459,7 +1464,7 @@ index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId,
 							  indcoloptions->values,
 							  stattargets,
 							  reloptionsDatum,
-							  INDEX_CREATE_SKIP_BUILD | INDEX_CREATE_CONCURRENT,
+							  flags,
 							  0,
 							  true, /* allow table to be a system catalog? */
 							  false,	/* is_internal? */
@@ -2453,7 +2458,8 @@ BuildIndexInfo(Relation index)
 					   indexStruct->indisready,
 					   false,
 					   index->rd_indam->amsummarizing,
-					   indexStruct->indisexclusion && indexStruct->indisunique);
+					   indexStruct->indisexclusion && indexStruct->indisunique,
+					   NULL, NULL, NULL);
 
 	/* fill in attribute numbers */
 	for (i = 0; i < numAtts; i++)
@@ -2513,7 +2519,8 @@ BuildDummyIndexInfo(Relation index)
 					   indexStruct->indisready,
 					   false,
 					   index->rd_indam->amsummarizing,
-					   indexStruct->indisexclusion && indexStruct->indisunique);
+					   indexStruct->indisexclusion && indexStruct->indisunique,
+					   NULL, NULL, NULL);
 
 	/* fill in attribute numbers */
 	for (i = 0; i < numAtts; i++)
diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c
index dd593ccbc1c..83edab38760 100644
--- a/src/backend/commands/indexcmds.c
+++ b/src/backend/commands/indexcmds.c
@@ -244,7 +244,8 @@ CheckIndexCompatible(Oid oldId,
 	 */
 	indexInfo = makeIndexInfo(numberOfAttributes, numberOfAttributes,
 							  accessMethodId, NIL, NIL, false, false,
-							  false, false, amsummarizing, isWithoutOverlaps);
+							  false, false, amsummarizing, isWithoutOverlaps,
+							  NULL, NULL, NULL);
 	typeIds = palloc_array(Oid, numberOfAttributes);
 	collationIds = palloc_array(Oid, numberOfAttributes);
 	opclassIds = palloc_array(Oid, numberOfAttributes);
@@ -931,7 +932,8 @@ DefineIndex(ParseState *pstate,
 							  !concurrent,
 							  concurrent,
 							  amissummarizing,
-							  stmt->iswithoutoverlaps);
+							  stmt->iswithoutoverlaps,
+							  NULL, NULL, NULL);
 
 	typeIds = palloc_array(Oid, numberOfAttributes);
 	collationIds = palloc_array(Oid, numberOfAttributes);
@@ -3989,10 +3991,11 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein
 			tablespaceid = indexRel->rd_rel->reltablespace;
 
 		/* Create new index definition based on given index */
-		newIndexId = index_concurrently_create_copy(heapRel,
-													idx->indexId,
-													tablespaceid,
-													concurrentName);
+		newIndexId = index_create_copy(heapRel,
+									   true,
+									   idx->indexId,
+									   tablespaceid,
+									   concurrentName);
 
 		/*
 		 * Now open the relation of the new index, a session-level lock is
diff --git a/src/backend/nodes/makefuncs.c b/src/backend/nodes/makefuncs.c
index 3cd35c5c457..8d23aa917e5 100644
--- a/src/backend/nodes/makefuncs.c
+++ b/src/backend/nodes/makefuncs.c
@@ -834,7 +834,8 @@ IndexInfo *
 makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions,
 			  List *predicates, bool unique, bool nulls_not_distinct,
 			  bool isready, bool concurrent, bool summarizing,
-			  bool withoutoverlaps)
+			  bool withoutoverlaps, Oid *exclusion_ops, Oid *exclusion_procs,
+			  uint16 *exclusion_strats)
 {
 	IndexInfo  *n = makeNode(IndexInfo);
 
@@ -863,9 +864,9 @@ makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions,
 	n->ii_PredicateState = NULL;
 
 	/* exclusion constraints */
-	n->ii_ExclusionOps = NULL;
-	n->ii_ExclusionProcs = NULL;
-	n->ii_ExclusionStrats = NULL;
+	n->ii_ExclusionOps = exclusion_ops;
+	n->ii_ExclusionProcs = exclusion_procs;
+	n->ii_ExclusionStrats = exclusion_strats;
 
 	/* speculative inserts */
 	n->ii_UniqueOps = NULL;
diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h
index 36b70689254..56a064ef444 100644
--- a/src/include/catalog/index.h
+++ b/src/include/catalog/index.h
@@ -101,10 +101,9 @@ extern Oid	index_create(Relation heapRelation,
 #define	INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS	(1 << 4)
 #define	INDEX_CONSTR_CREATE_WITHOUT_OVERLAPS (1 << 5)
 
-extern Oid	index_concurrently_create_copy(Relation heapRelation,
-										   Oid oldIndexId,
-										   Oid tablespaceOid,
-										   const char *newName);
+extern Oid	index_create_copy(Relation heapRelation, bool concurrently,
+							  Oid oldIndexId, Oid tablespaceOid,
+							  const char *newName);
 
 extern void index_concurrently_build(Oid heapRelationId,
 									 Oid indexRelationId);
diff --git a/src/include/nodes/makefuncs.h b/src/include/nodes/makefuncs.h
index bf54d39feb0..40ec249a7a1 100644
--- a/src/include/nodes/makefuncs.h
+++ b/src/include/nodes/makefuncs.h
@@ -99,7 +99,9 @@ extern IndexInfo *makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid,
 								List *expressions, List *predicates,
 								bool unique, bool nulls_not_distinct,
 								bool isready, bool concurrent,
-								bool summarizing, bool withoutoverlaps);
+								bool summarizing, bool withoutoverlaps,
+								Oid *exclusion_ops, Oid *exclusion_procs,
+								uint16 *exclusion_strats);
 
 extern Node *makeStringConst(char *str, int location);
 extern DefElem *makeDefElem(char *name, Node *arg, int location);
-- 
2.47.3


--gwom7bl7ogtszo4k
Content-Type: text/x-diff; charset=utf-8
Content-Disposition: attachment;
	filename="v44-0002-Do-not-dereference-varattrib_4b-in-VARSIZE_4B.patch"



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

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ 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; 153+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)

DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.

This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.

The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.

Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().

DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.

AlterRole() does not need the fix 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] 153+ messages in thread


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

Thread overview: 153+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-03-24 18:02 [PATCH v44 01/10] Make index_concurrently_create_copy more general Álvaro Herrera <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH 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 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 v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH 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 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 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 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 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 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 v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH 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 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 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 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 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 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 v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH 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 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 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 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]>

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