agora inbox for pgsql-hackers@postgresql.org  
help / color / mirror / Atom feed
Fix races conditions in DropRole() and GrantRole()
12+ messages / 2 participants
[nested] [flat]

* Fix races conditions in DropRole() and GrantRole()
@ 2026-07-04 07:47 Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-06 13:22 ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-09 04:45 ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  0 siblings, 2 replies; 12+ messages in thread

From: Bertrand Drouvot @ 2026-07-04 07:47 UTC (permalink / raw)
  To: pgsql-hackers@lists.postgresql.org

Hi hackers,

While working on [1], I observed that DropRole() and GrantRole() have the same
"use stale data after the lock is acquired" issues.

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

Examples:

1/ DROP ROLE + concurrent DROP ROLE

CREATE ROLE testrole;
gdb breakpoint at user.c:1198 (before LockSharedObject) on session 1

session 1: DROP ROLE testrole;
session 1 is paused by the breakpoint
session 2: DROP ROLE testrole;
continue session 1 produces:
ERROR: could not find tuple for role 24662

2/ GRANT ROLE + concurrent DROP ROLE

CREATE ROLE testrole;
CREATE ROLE testmember;
gdb breakpoint at user.c:1716 (before LockSharedObject) on session 1

session 1: GRANT testrole TO testmember;
session is paused by the breakpoint
session 2: DROP ROLE testrole;
continue session 1: GRANT ROLE succeeds

It produces an orphaned pg_auth_members entry:

postgres=#   SELECT m.member::regrole, m.roleid, r.rolname
  FROM pg_auth_members m
  LEFT JOIN pg_roles r ON m.roleid = r.oid
  WHERE r.oid IS NULL;
   member   | roleid | rolname
------------+--------+---------
 testmember |  16386 |


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

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

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

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

Remark:

AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.

[1]: https://postgr.es/m/akZUpiDa1UfmzYxL%40bdtpg

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com

Attachments:

  [text/x-diff] v1-0001-Add-RoleNameGetOid-with-invalidation-based-retry-.patch (12.8K, ../../aki6fMNLUx6+BR8K@bdtpg/2-v1-0001-Add-RoleNameGetOid-with-invalidation-based-retry-.patch)
  download | inline diff:
From 7b7b46ea877dfb7be33b842bf13711adfbbd1b55 Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Sat, 4 Jul 2026 04:47:22 +0000
Subject: [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop
 for DropRole()/GrantRole()

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

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

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

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

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

AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
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

^ permalink  raw  reply  [nested|flat] 12+ messages in thread

* Re: Fix races conditions in DropRole() and GrantRole()
  2026-07-04 07:47 Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
@ 2026-07-06 13:22 ` Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  1 sibling, 0 replies; 12+ messages in thread

From: Bertrand Drouvot @ 2026-07-06 13:22 UTC (permalink / raw)
  To: pgsql-hackers@lists.postgresql.org; +Cc: Tom Lane <tgl@sss.pgh.pa.us>

Hi,

On Sat, Jul 04, 2026 at 07:47:08AM +0000, Bertrand Drouvot wrote:
> The patch attached fixes the races by using the same approach as
> RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking
> (via a caller-supplied callback), and lock acquisition inside a retry loop driven
> by SharedInvalidMessageCounter. If invalidation messages arrive between name
> resolution and locking, indicating concurrent DDL, the function retries.

Also I think we could make use of the same approach to fix one of the issue that
was discussed in [1], means:

"
create role my_group;
create role dropped_member;

Session 1: begin;grant my_group to dropped_member;
Session 2: drop role dropped_member;
Session 1: commit;
"

producing an orphaned pg_auth_members entry:

postgres=# SELECT m.member, m.roleid, r.rolname
    FROM pg_auth_members m
    LEFT JOIN pg_roles r ON m.member = r.oid
    WHERE r.oid IS NULL;
 member | roleid | rolname
--------+--------+---------
  16385 |  16384 |
(1 row)


0002 fixes this by acquiring AccessShareLock on each resolved role within
roleSpecsToIds(), ensuring the role cannot be dropped while any caller is using
its OID.

It also fixes other cases that would produce orphaned pg_auth_members entries,
like "ALTER GROUP my_group ADD USER dropped_member" or
"CREATE ROLE new_group ROLE dropped_member" with a concurrent DROP of
dropped_member.

Note that DropOwnedObjects() and ReassignOwnedObjects() check has_privs_of_role()
after the lock is acquired. Moving those into a callback could be done if we feel
the need.

[1]: https://postgr.es/m/CAM6Zo8woa62ZFHtMKox6a4jb8qQ%3Dw87R2L0K8347iE-juQL2EA%40mail.gmail.com

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com

Attachments:

  [text/x-diff] v2-0001-Add-RoleNameGetOid-with-invalidation-based-retry-.patch (12.9K, ../../akusH9lDGd6kx2rz@bdtpg/2-v2-0001-Add-RoleNameGetOid-with-invalidation-based-retry-.patch)
  download | inline diff:
From 61a6909c6e2a570e6fef12d14c2737b5fe78572a Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Mon, 6 Jul 2026 08:28:41 +0000
Subject: [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry
 loop for DropRole()/GrantRole()

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

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

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

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

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

AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
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

  [text/x-diff] v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch (6.3K, ../../akusH9lDGd6kx2rz@bdtpg/3-v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch)
  download | inline diff:
From 3731adf4458ca43c4b2461f1e0e1c380e9fbc0e9 Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Mon, 6 Jul 2026 08:28:41 +0000
Subject: [PATCH v2 2/2] Protect role resolution in roleSpecsToIds() against
 concurrent DROP

roleSpecsToIds() resolves role names to OIDs without acquiring any lock.
A concurrent DROP ROLE that commits between this resolution and the caller's use
of the OID leaves the caller operating on a stale OID, which can create orphaned
pg_auth_members entries.

Fix this by acquiring AccessShareLock on each resolved role within
roleSpecsToIds(), ensuring the role cannot be dropped while any caller is using
its OID.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Reported-by: Virender Singla <virender.cse@gmail.com>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
Discussion: https://postgr.es/m/CAM6Zo8woa62ZFHtMKox6a4jb8qQ%3Dw87R2L0K8347iE-juQL2EA%40mail.gmail.com
---
 src/backend/commands/user.c                   | 13 +++++-
 .../expected/role-membership-drop-member.out  | 36 ++++++++++++++++
 src/test/isolation/isolation_schedule         |  1 +
 .../specs/role-membership-drop-member.spec    | 43 +++++++++++++++++++
 4 files changed, 92 insertions(+), 1 deletion(-)
  13.8% src/backend/commands/
  42.9% src/test/isolation/expected/
  42.2% src/test/isolation/specs/

diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index 5b869e91c17..05ec753f4f0 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -1778,6 +1778,8 @@ ReassignOwnedObjects(ReassignOwnedStmt *stmt)
  * roleSpecsToIds
  *
  * Given a list of RoleSpecs, generate a list of role OIDs in the same order.
+ * Each role is locked with AccessShareLock to prevent concurrent DROP ROLE
+ * from removing it between resolution and the caller's catalog update.
  *
  * ROLESPEC_PUBLIC is not allowed.
  */
@@ -1792,7 +1794,16 @@ roleSpecsToIds(List *memberNames)
 		RoleSpec   *rolespec = lfirst_node(RoleSpec, l);
 		Oid			roleid;
 
-		roleid = get_rolespec_oid(rolespec, false);
+		if (rolespec->roletype == ROLESPEC_CSTRING)
+			roleid = RoleNameGetOid(rolespec->rolename,
+									AccessShareLock, false,
+									NULL, NULL);
+		else
+		{
+			roleid = get_rolespec_oid(rolespec, false);
+			LockSharedObject(AuthIdRelationId, roleid, 0,
+							 AccessShareLock);
+		}
 		result = lappend_oid(result, roleid);
 	}
 	return result;
diff --git a/src/test/isolation/expected/role-membership-drop-member.out b/src/test/isolation/expected/role-membership-drop-member.out
new file mode 100644
index 00000000000..e6cae59d2c9
--- /dev/null
+++ b/src/test/isolation/expected/role-membership-drop-member.out
@@ -0,0 +1,36 @@
+Parsed test spec with 2 sessions
+
+starting permutation: s1_begin s1_grant s2_drop_member s1_commit
+step s1_begin: BEGIN;
+step s1_grant: GRANT regress_role_group TO regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+
+starting permutation: s1_begin s1_alter_add s2_drop_member s1_commit
+step s1_begin: BEGIN;
+step s1_alter_add: ALTER GROUP regress_role_group ADD USER regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+
+starting permutation: s1_begin s1_create_role s2_drop_member s1_commit
+step s1_begin: BEGIN;
+step s1_create_role: CREATE ROLE regress_role_new ROLE regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+
+starting permutation: s1_begin s1_drop_owned s2_drop_member s1_commit
+step s1_begin: BEGIN;
+step s1_drop_owned: DROP OWNED BY regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+
+starting permutation: s1_begin s1_reassign_owned s2_drop_member s1_commit
+step s1_begin: BEGIN;
+step s1_reassign_owned: REASSIGN OWNED BY regress_role_member TO regress_role_group;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
diff --git a/src/test/isolation/isolation_schedule b/src/test/isolation/isolation_schedule
index b8ebe92553c..8fb8b52b77f 100644
--- a/src/test/isolation/isolation_schedule
+++ b/src/test/isolation/isolation_schedule
@@ -128,3 +128,4 @@ test: matview-write-skew
 test: lock-nowait
 test: for-portion-of
 test: ddl-dependency-locking
+test: role-membership-drop-member
diff --git a/src/test/isolation/specs/role-membership-drop-member.spec b/src/test/isolation/specs/role-membership-drop-member.spec
new file mode 100644
index 00000000000..e0140826e52
--- /dev/null
+++ b/src/test/isolation/specs/role-membership-drop-member.spec
@@ -0,0 +1,43 @@
+# Test that role membership commands properly lock the grantee/member
+# role to prevent concurrent DROP ROLE from creating orphaned # pg_auth_members
+# entries.
+
+setup
+{
+	CREATE ROLE regress_role_group;
+	CREATE ROLE regress_role_member;
+}
+
+teardown
+{
+	DROP ROLE IF EXISTS regress_role_group;
+	DROP ROLE IF EXISTS regress_role_member;
+	DROP ROLE IF EXISTS regress_role_new;
+}
+
+session s1
+step s1_begin		{ BEGIN; }
+step s1_grant		{ GRANT regress_role_group TO regress_role_member; }
+step s1_alter_add	{ ALTER GROUP regress_role_group ADD USER regress_role_member; }
+step s1_create_role	{ CREATE ROLE regress_role_new ROLE regress_role_member; }
+step s1_drop_owned	{ DROP OWNED BY regress_role_member; }
+step s1_reassign_owned	{ REASSIGN OWNED BY regress_role_member TO regress_role_group; }
+step s1_commit		{ COMMIT; }
+
+session s2
+step s2_drop_member	{ DROP ROLE regress_role_member; }
+
+# GRANT role TO member - concurrent DROP of the member
+permutation s1_begin s1_grant s2_drop_member s1_commit
+
+# ALTER ROLE ADD USER - concurrent DROP of the member
+permutation s1_begin s1_alter_add s2_drop_member s1_commit
+
+# CREATE ROLE ... ROLE member - concurrent DROP of the member
+permutation s1_begin s1_create_role s2_drop_member s1_commit
+
+# DROP OWNED BY role - concurrent DROP of the role
+permutation s1_begin s1_drop_owned s2_drop_member s1_commit
+
+# REASSIGN OWNED BY role - concurrent DROP of the role
+permutation s1_begin s1_reassign_owned s2_drop_member s1_commit
-- 
2.34.1

^ permalink  raw  reply  [nested|flat] 12+ messages in thread

* Re: Fix races conditions in DropRole() and GrantRole()
  2026-07-04 07:47 Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
@ 2026-07-09 04:45 ` surya poondla <suryapoondla4@gmail.com>
  2026-07-09 07:05   ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  1 sibling, 1 reply; 12+ messages in thread

From: surya poondla @ 2026-07-09 04:45 UTC (permalink / raw)
  To: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Bertrand,


Thanks for the patch set. I agree the races are real, and reusing the
RangeVarGetRelidExtended() invalidation-retry idiom is a good fit, the
retry loop looks correct and closes the window for the covered paths.

I have a few comments
1. The 0002 patch creates a new deadlock. GrantRole() now locks the member
via roleSpecsToIds() (AccessShareLock, before the granted-role loop) and
then the granted role via RoleNameGetOid()
(ShareUpdateExclusiveLock).
DROP ROLE takes AccessExclusiveLock per role in list order.
Because AccessExclusiveLock conflicts with everything, this creates a
lock-order cycle that did not exist before.
For example say we have 2 concurrent sessions:
S1: GRANT g TO m;       S2: DROP ROLE g, m;
1. S1 acquires AccessShareLock(m)
2. S2 acquires AccessExclusiveLock(g)
3. S1 waits ShareUpdateExclusiveLock(g)  -- blocked by S2
4. S2 waits AccessExclusiveLock(m)           -- blocked by S1
-> deadlock
Pre-patch, GRANT didn't lock the member, so S2 never blocked S1.
The same expanded locking applies to CREATE ROLE ... ROLE and the ALTER
ROLE ... ADD/DROP USER (ALTER GROUP) path,
which also goes through roleSpecsToIds().
Swapping a silent orphan for a detected deadlock is arguably fine, but it's
a behavior change, could you document the lock ordering, and maybe have
DROP ROLE lock in a canonical (OID-sorted) order?

2. DROP ROLE now blocks on unrelated long transactions. The
AccessShareLock from
roleSpecsToIds() is held to commit,
so an open txn that ran GRANT/CREATE ROLE ... ROLE/REASSIGN OWNED touching
X, blocks a concurrent DROP ROLE X.  This is intended behavior, but worth a
note in the commit message/docs.

3. For non-cstring role specs, the else-branch (CURRENT_USER/SESSION_USER)
 does:
roleid = get_rolespec_oid(rolespec, false);
LockSharedObject(AuthIdRelationId, roleid, 0, AccessShareLock);
get_rolespec_oid() returns the backend's cached session OID (GetUserId())
rather than re-resolving a name, so there is no retry mechanism and
no post-lock existence check.
Since DropRole() only blocks dropping the *dropping* session's own user,
nothing stops another session from dropping this session's login role, so
"GRANT g TO CURRENT_USER" can still orphan.
RoleNameCallbackForDropRole() already does this by doing a re-check (a
SearchSysCache1(AUTHOID) after resolving, erroring if the tuple is gone),
so the else-branch could do the same after locking.

4. In role-membership-drop-member.spec only checks that the concurrent DROP
waits; it never asserts the outcome, so it would still pass if the locking
left an orphan. A final step selecting for orphaned rows would make it
detect outcome regressions, e.g.

       SELECT m.roleid, m.member, m.grantor
        FROM pg_auth_members m
        LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
        LEFT JOIN pg_authid me ON m.member  = me.oid
        LEFT JOIN pg_authid gr ON m.grantor = gr.oid
       WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;

Nit: the spec header comment has a stray '#' ("orphaned # pg_auth_members").

Regards,
Surya Poondla

^ permalink  raw  reply  [nested|flat] 12+ messages in thread

* Re: Fix races conditions in DropRole() and GrantRole()
  2026-07-04 07:47 Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-09 04:45 ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
@ 2026-07-09 07:05   ` Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-10 21:42     ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  0 siblings, 1 reply; 12+ messages in thread

From: Bertrand Drouvot @ 2026-07-09 07:05 UTC (permalink / raw)
  To: surya poondla <suryapoondla4@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Surya,

On Wed, Jul 08, 2026 at 09:45:34PM -0700, surya poondla wrote:
> Hi Bertrand,
> 
> 
> Thanks for the patch set. I agree the races are real, and reusing the
> RangeVarGetRelidExtended() invalidation-retry idiom is a good fit, the
> retry loop looks correct and closes the window for the covered paths.

Thanks for looking at it!

> Swapping a silent orphan for a detected deadlock is arguably fine, but it's
> a behavior change, could you document the lock ordering

Nice catch! I think that a rare deadlock is better than a rare orphaned entry,
so I added a note in the commit message.

>, and maybe have
> DROP ROLE lock in a canonical (OID-sorted) order?

That would add extra complexity and I'm not sure that sorting only in DROP ROLE
would fully solve it.

Also, I don't think there is precedent in the code tree. So I think we should keep
it simple and just mention it in the commit message.

> 2. DROP ROLE now blocks on unrelated long transactions. The
> AccessShareLock from
> roleSpecsToIds() is held to commit,
> so an open txn that ran GRANT/CREATE ROLE ... ROLE/REASSIGN OWNED touching
> X, blocks a concurrent DROP ROLE X.  This is intended behavior, but worth a
> note in the commit message/docs.

Right, added in the commit message. Not sure it's worth an addition in the doc
given that existing locking behavior for role commands is not documented there
either.

> 3. For non-cstring role specs, the else-branch (CURRENT_USER/SESSION_USER)
>  does:
> roleid = get_rolespec_oid(rolespec, false);
> LockSharedObject(AuthIdRelationId, roleid, 0, AccessShareLock);
> get_rolespec_oid() returns the backend's cached session OID (GetUserId())
> rather than re-resolving a name, so there is no retry mechanism and
> no post-lock existence check.
> Since DropRole() only blocks dropping the *dropping* session's own user,
> nothing stops another session from dropping this session's login role, so
> "GRANT g TO CURRENT_USER" can still orphan.
> RoleNameCallbackForDropRole() already does this by doing a re-check (a
> SearchSysCache1(AUTHOID) after resolving, erroring if the tuple is gone),
> so the else-branch could do the same after locking.

Good point, done in the attached.

> 
> 4. In role-membership-drop-member.spec only checks that the concurrent DROP
> waits; it never asserts the outcome, so it would still pass if the locking
> left an orphan.

I'm not sure how an orphan could be created if we ensure proper locking. That
said this extra check does not hurt, so added for the permutations that would
produce orphans without the patch.

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com

Attachments:

  [text/x-diff] v3-0001-Add-RoleNameGetOid-with-invalidation-based-retry-.patch (13.0K, ../../ak9IUpaxNlhAflKU@bdtpg/2-v3-0001-Add-RoleNameGetOid-with-invalidation-based-retry-.patch)
  download | inline diff:
From 1b29c74b42022a0586807cbcfe0b004e72044666 Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Mon, 6 Jul 2026 08:28:41 +0000
Subject: [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry
 loop for DropRole()/GrantRole()

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

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

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

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

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

AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Reviewed-by: Surya Poondla <suryapoondla4@gmail.com>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
 src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
 src/include/commands/user.h |   9 ++
 2 files changed, 193 insertions(+), 64 deletions(-)
  95.5% src/backend/commands/
   4.4% src/include/commands/

diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
 #include "miscadmin.h"
 #include "port/pg_bitutils.h"
 #include "storage/lmgr.h"
+#include "storage/sinval.h"
 #include "utils/acl.h"
 #include "utils/builtins.h"
 #include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
 								  bool revoke_admin_option_only,
 								  DropBehavior behavior);
 static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+										Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+										 Oid oldroleid, void *callback_arg);
 
 
 /* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
 }
 
 
+/*
+ * RoleNameGetOid
+ *		Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+			   RoleNameGetOidCallback callback, void *callback_arg)
+{
+	uint64		inval_count;
+	Oid			roleid;
+	Oid			oldroleid = InvalidOid;
+	bool		retry = false;
+
+	for (;;)
+	{
+		/*
+		 * Remember the current invalidation count so we can detect concurrent
+		 * DDL after locking.
+		 */
+		inval_count = SharedInvalidMessageCounter;
+
+		/* Look up the role name */
+		roleid = get_role_oid(rolename, true);
+
+		if (!OidIsValid(roleid))
+		{
+			if (retry)
+				UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+			if (!missing_ok)
+				ereport(ERROR,
+						(errcode(ERRCODE_UNDEFINED_OBJECT),
+						 errmsg("role \"%s\" does not exist", rolename)));
+			return InvalidOid;
+		}
+
+		/*
+		 * Invoke caller-supplied callback before locking. This is a good
+		 * place to check permissions: we haven't taken the lock yet, but we
+		 * know the OID we intend to lock. If concurrent DDL changes things,
+		 * the callback will be invoked again on the next iteration.
+		 */
+		if (callback)
+			callback(rolename, roleid, oldroleid, callback_arg);
+
+		/*
+		 * If upon retry we get back the same OID, the invalidation messages
+		 * did not change the final answer. So we're done.
+		 *
+		 * If we got a different OID, we've locked the role that used to have
+		 * this name rather than the one that does now. Release the old lock.
+		 */
+		if (retry)
+		{
+			if (roleid == oldroleid)
+				break;
+			UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+		}
+
+		/* Lock the role */
+		LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+		/* If no invalidation messages were processed, we're done */
+		if (inval_count == SharedInvalidMessageCounter)
+			break;
+
+		/* Something may have changed, retry */
+		retry = true;
+		oldroleid = roleid;
+	}
+
+	return roleid;
+}
+
+
 /*
  * CREATE ROLE
  */
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
 }
 
 
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+							Oid oldroleid, void *callback_arg)
+{
+	HeapTuple	tuple;
+	Form_pg_authid roleform;
+
+	if (roleid == GetUserId())
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_IN_USE),
+				 errmsg("current user cannot be dropped")));
+	if (roleid == GetOuterUserId())
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_IN_USE),
+				 errmsg("current user cannot be dropped")));
+	if (roleid == GetSessionUserId())
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_IN_USE),
+				 errmsg("session user cannot be dropped")));
+
+	tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+	if (!HeapTupleIsValid(tuple))
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("role \"%s\" does not exist", rolename)));
+
+	roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+	/*
+	 * For safety's sake, we allow createrole holders to drop ordinary roles
+	 * but not superuser roles, and only if they also have ADMIN OPTION.
+	 */
+	if (roleform->rolsuper && !superuser())
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("permission denied to drop role"),
+				 errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+						   "SUPERUSER", "SUPERUSER")));
+	if (!is_admin_of_role(GetUserId(), roleid))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("permission denied to drop role"),
+				 errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+						   "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+	ReleaseSysCache(tuple);
+}
+
+
 /*
  * DROP ROLE
  */
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
 	{
 		RoleSpec   *rolspec = lfirst(item);
 		char	   *role;
-		HeapTuple	tuple,
-					tmp_tuple;
-		Form_pg_authid roleform;
+		HeapTuple	tmp_tuple;
 		ScanKeyData scankey;
 		SysScanDesc sscan;
 		Oid			roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
 					 errmsg("cannot use special role specifier in DROP ROLE")));
 		role = rolspec->rolename;
 
-		tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
-		if (!HeapTupleIsValid(tuple))
-		{
-			if (!stmt->missing_ok)
-			{
-				ereport(ERROR,
-						(errcode(ERRCODE_UNDEFINED_OBJECT),
-						 errmsg("role \"%s\" does not exist", role)));
-			}
-			else
-			{
-				ereport(NOTICE,
-						(errmsg("role \"%s\" does not exist, skipping",
-								role)));
-			}
+		/*
+		 * Use RoleNameGetOid to resolve the name, check permissions, and lock
+		 * the role atomically with a retry loop. This prevents race
+		 * conditions where a concurrent DROP or ALTER commits between name
+		 * resolution and lock acquisition.
+		 */
+		roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+								RoleNameCallbackForDropRole, NULL);
 
+		if (!OidIsValid(roleid))
+		{
+			/* missing_ok case: role doesn't exist */
+			ereport(NOTICE,
+					(errmsg("role \"%s\" does not exist, skipping",
+							role)));
 			continue;
 		}
 
-		roleform = (Form_pg_authid) GETSTRUCT(tuple);
-		roleid = roleform->oid;
-
-		if (roleid == GetUserId())
-			ereport(ERROR,
-					(errcode(ERRCODE_OBJECT_IN_USE),
-					 errmsg("current user cannot be dropped")));
-		if (roleid == GetOuterUserId())
-			ereport(ERROR,
-					(errcode(ERRCODE_OBJECT_IN_USE),
-					 errmsg("current user cannot be dropped")));
-		if (roleid == GetSessionUserId())
-			ereport(ERROR,
-					(errcode(ERRCODE_OBJECT_IN_USE),
-					 errmsg("session user cannot be dropped")));
-
-		/*
-		 * For safety's sake, we allow createrole holders to drop ordinary
-		 * roles but not superuser roles, and only if they also have ADMIN
-		 * OPTION.
-		 */
-		if (roleform->rolsuper && !superuser())
-			ereport(ERROR,
-					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
-					 errmsg("permission denied to drop role"),
-					 errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
-							   "SUPERUSER", "SUPERUSER")));
-		if (!is_admin_of_role(GetUserId(), roleid))
-			ereport(ERROR,
-					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
-					 errmsg("permission denied to drop role"),
-					 errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
-							   "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
 		/* DROP hook for the role being removed */
 		InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
 
-		/* Don't leak the syscache tuple */
-		ReleaseSysCache(tuple);
-
-		/*
-		 * Lock the role, so nobody can add dependencies to her while we drop
-		 * her.  We keep the lock until the end of transaction.
-		 */
-		LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
 		/*
 		 * If there is a pg_auth_members entry that has one of the roles to be
 		 * dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
 	return address;
 }
 
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+							 Oid oldroleid, void *callback_arg)
+{
+	bool		is_grant = *((bool *) callback_arg);
+	Oid			currentUserId = GetUserId();
+
+	check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
 /*
  * GrantRoleStmt
  *
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
 					(errcode(ERRCODE_INVALID_GRANT_OPERATION),
 					 errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
 
-		roleid = get_role_oid(rolename, false);
-		check_role_membership_authorization(currentUserId,
-											roleid, stmt->is_grant);
+		/*
+		 * Use RoleNameGetOid to resolve the name, check permissions, and lock
+		 * the role atomically with a retry loop. This prevents race
+		 * conditions where a concurrent DROP commits between name resolution
+		 * and lock acquisition.
+		 */
+		roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+								RoleNameCallbackForGrantRole, &stmt->is_grant);
 		if (stmt->is_grant)
 			AddRoleMems(currentUserId, rolename, roleid,
 						stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
 extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
 extern PGDLLIMPORT char *createrole_self_grant;
 
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+										Oid oldroleid, void *callback_arg);
+
+extern Oid	RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+						   bool missing_ok,
+						   RoleNameGetOidCallback callback,
+						   void *callback_arg);
+
 /* Hook to check passwords in CreateRole() and AlterRole() */
 typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
 
-- 
2.34.1

  [text/x-diff] v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch (8.3K, ../../ak9IUpaxNlhAflKU@bdtpg/3-v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch)
  download | inline diff:
From 77b64cab87d9279f477cb50674e62b3ef4dbdbdd Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Mon, 6 Jul 2026 08:28:41 +0000
Subject: [PATCH v3 2/2] Protect role resolution in roleSpecsToIds() against
 concurrent DROP

roleSpecsToIds() resolves role names to OIDs without acquiring any lock.
A concurrent DROP ROLE that commits between this resolution and the caller's use
of the OID leaves the caller operating on a stale OID, which can create orphaned
pg_auth_members entries.

Fix this by acquiring AccessShareLock on each resolved role within
roleSpecsToIds(), ensuring the role cannot be dropped while any caller is using
its OID.

The AccessShareLock is held until end of transaction, so an open transaction
that performed GRANT, CREATE ROLE ... ROLE, or REASSIGN OWNED BY will block a
concurrent DROP ROLE on the same role until it commits.

Note that this introduces a potential deadlock between GRANT and DROP ROLE
when both target overlapping roles. The deadlock is detected and one session is
aborted with an error, which is preferable to the pre-patch behavior of silently
creating orphaned catalog entries.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Reported-by: Virender Singla <virender.cse@gmail.com>
Reviewed-by: Surya Poondla <suryapoondla4@gmail.com>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
Discussion: https://postgr.es/m/CAM6Zo8woa62ZFHtMKox6a4jb8qQ%3Dw87R2L0K8347iE-juQL2EA%40mail.gmail.com
---
 src/backend/commands/user.c                   | 21 +++++-
 .../expected/role-membership-drop-member.out  | 75 +++++++++++++++++++
 src/test/isolation/isolation_schedule         |  1 +
 .../specs/role-membership-drop-member.spec    | 51 +++++++++++++
 4 files changed, 147 insertions(+), 1 deletion(-)
  14.9% src/backend/commands/
  48.1% src/test/isolation/expected/
  36.1% src/test/isolation/specs/

diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index 5b869e91c17..375fb527af2 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -1778,6 +1778,8 @@ ReassignOwnedObjects(ReassignOwnedStmt *stmt)
  * roleSpecsToIds
  *
  * Given a list of RoleSpecs, generate a list of role OIDs in the same order.
+ * Each role is locked with AccessShareLock to prevent concurrent DROP ROLE
+ * from removing it between resolution and the caller's catalog update.
  *
  * ROLESPEC_PUBLIC is not allowed.
  */
@@ -1792,7 +1794,24 @@ roleSpecsToIds(List *memberNames)
 		RoleSpec   *rolespec = lfirst_node(RoleSpec, l);
 		Oid			roleid;
 
-		roleid = get_rolespec_oid(rolespec, false);
+		if (rolespec->roletype == ROLESPEC_CSTRING)
+			roleid = RoleNameGetOid(rolespec->rolename,
+									AccessShareLock, false,
+									NULL, NULL);
+		else
+		{
+			roleid = get_rolespec_oid(rolespec, false);
+			LockSharedObject(AuthIdRelationId, roleid, 0,
+							 AccessShareLock);
+
+			/* Recheck that the role still exists after locking. */
+			if (!SearchSysCacheExists1(AUTHOID, ObjectIdGetDatum(roleid)))
+				ereport(ERROR,
+						(errcode(ERRCODE_UNDEFINED_OBJECT),
+						 errmsg("role \"%s\" does not exist",
+								get_rolespec_name(rolespec))));
+		}
+
 		result = lappend_oid(result, roleid);
 	}
 	return result;
diff --git a/src/test/isolation/expected/role-membership-drop-member.out b/src/test/isolation/expected/role-membership-drop-member.out
new file mode 100644
index 00000000000..5b267ea32c2
--- /dev/null
+++ b/src/test/isolation/expected/role-membership-drop-member.out
@@ -0,0 +1,75 @@
+Parsed test spec with 2 sessions
+
+starting permutation: s1_begin s1_grant s2_drop_member s1_commit s2_check_orphans
+step s1_begin: BEGIN;
+step s1_grant: GRANT regress_role_group TO regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+step s2_check_orphans: 
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+
+count
+-----
+    0
+(1 row)
+
+
+starting permutation: s1_begin s1_alter_add s2_drop_member s1_commit s2_check_orphans
+step s1_begin: BEGIN;
+step s1_alter_add: ALTER GROUP regress_role_group ADD USER regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+step s2_check_orphans: 
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+
+count
+-----
+    0
+(1 row)
+
+
+starting permutation: s1_begin s1_create_role s2_drop_member s1_commit s2_check_orphans
+step s1_begin: BEGIN;
+step s1_create_role: CREATE ROLE regress_role_new ROLE regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+step s2_check_orphans: 
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+
+count
+-----
+    0
+(1 row)
+
+
+starting permutation: s1_begin s1_drop_owned s2_drop_member s1_commit
+step s1_begin: BEGIN;
+step s1_drop_owned: DROP OWNED BY regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+
+starting permutation: s1_begin s1_reassign_owned s2_drop_member s1_commit
+step s1_begin: BEGIN;
+step s1_reassign_owned: REASSIGN OWNED BY regress_role_member TO regress_role_group;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
diff --git a/src/test/isolation/isolation_schedule b/src/test/isolation/isolation_schedule
index b8ebe92553c..8fb8b52b77f 100644
--- a/src/test/isolation/isolation_schedule
+++ b/src/test/isolation/isolation_schedule
@@ -128,3 +128,4 @@ test: matview-write-skew
 test: lock-nowait
 test: for-portion-of
 test: ddl-dependency-locking
+test: role-membership-drop-member
diff --git a/src/test/isolation/specs/role-membership-drop-member.spec b/src/test/isolation/specs/role-membership-drop-member.spec
new file mode 100644
index 00000000000..989fe996249
--- /dev/null
+++ b/src/test/isolation/specs/role-membership-drop-member.spec
@@ -0,0 +1,51 @@
+# Test that role membership commands properly lock the grantee/member
+# role to prevent concurrent DROP ROLE from creating orphaned pg_auth_members
+# entries, or from operating on a stale OID.
+
+setup
+{
+	CREATE ROLE regress_role_group;
+	CREATE ROLE regress_role_member;
+}
+
+teardown
+{
+	DROP ROLE IF EXISTS regress_role_group;
+	DROP ROLE IF EXISTS regress_role_member;
+	DROP ROLE IF EXISTS regress_role_new;
+}
+
+session s1
+step s1_begin		{ BEGIN; }
+step s1_grant		{ GRANT regress_role_group TO regress_role_member; }
+step s1_alter_add	{ ALTER GROUP regress_role_group ADD USER regress_role_member; }
+step s1_create_role	{ CREATE ROLE regress_role_new ROLE regress_role_member; }
+step s1_drop_owned	{ DROP OWNED BY regress_role_member; }
+step s1_reassign_owned	{ REASSIGN OWNED BY regress_role_member TO regress_role_group; }
+step s1_commit		{ COMMIT; }
+
+session s2
+step s2_drop_member	{ DROP ROLE regress_role_member; }
+step s2_check_orphans	{
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+}
+
+# GRANT role TO member - concurrent DROP of the member
+permutation s1_begin s1_grant s2_drop_member s1_commit s2_check_orphans
+
+# ALTER GROUP ADD USER - concurrent DROP of the member
+permutation s1_begin s1_alter_add s2_drop_member s1_commit s2_check_orphans
+
+# CREATE ROLE ... ROLE member - concurrent DROP of the member
+permutation s1_begin s1_create_role s2_drop_member s1_commit s2_check_orphans
+
+# DROP OWNED BY role - concurrent DROP of the role
+permutation s1_begin s1_drop_owned s2_drop_member s1_commit
+
+# REASSIGN OWNED BY role - concurrent DROP of the role
+permutation s1_begin s1_reassign_owned s2_drop_member s1_commit
-- 
2.34.1

^ permalink  raw  reply  [nested|flat] 12+ messages in thread

* Re: Fix races conditions in DropRole() and GrantRole()
  2026-07-04 07:47 Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-09 04:45 ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-09 07:05   ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
@ 2026-07-10 21:42     ` surya poondla <suryapoondla4@gmail.com>
  2026-07-15 03:37       ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  0 siblings, 1 reply; 12+ messages in thread

From: surya poondla @ 2026-07-10 21:42 UTC (permalink / raw)
  To: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Bertrand,

Thanks for the v3 patch. The commit-message notes on the deadlock, the DROP
ROLE's blocking behavior, and the orphan-count checks in the isolation
test, all
look good to me.

Couple of comments on the new recheck in roleSpecsToIds():

1. In the error path, the else-branch currently does:

       if (!SearchSysCacheExists1(AUTHOID, ObjectIdGetDatum(roleid)))
           ereport(ERROR,
                   (errcode(ERRCODE_UNDEFINED_OBJECT),
                    errmsg("role \"%s\" does not exist",
                           get_rolespec_name(rolespec))));

The existence check itself is correct, but get_rolespec_name(rolespec)
calls get_rolespec_tuple(), which for CURRENT_USER/SESSION_USER does
SearchSysCache1(AUTHOID, GetUserId()) and, if the tuple is missing, throws
elog(ERROR, "cache lookup failed for role %u").
Since we only reach this branch because the role no longer exists, building
the message re-looks-up the dropped role and fails with that internal error
instead of the intended "role ... does not exist" i.e. it emits exactly the
kind of internal error this patch set is meant to remove.

Instead we can report the OID and it avoids the re-lookup entirely, e.g.

       if (!SearchSysCacheExists1(AUTHOID, ObjectIdGetDatum(roleid)))
           ereport(ERROR,
                   (errcode(ERRCODE_UNDEFINED_OBJECT),
                    errmsg("role with OID %u does not exist", roleid)));

Capturing get_rolespec_name() before locking would only help the
concurrent-drop case.
If the session's own role was already dropped earlier, get_rolespec_oid()
still returns the stale cached OID and
get_rolespec_name() would fail the same way, so the OID form is the robust
one.

2. The new s2_check_orphans permutations all use named roles, which go
through the RoleNameGetOid() (CSTRING) path. None exercise the
CURRENT_USER/SESSION_USER else-branch that the recheck was added for.
A permutation like "GRANT g TO CURRENT_USER" with a concurrent drop of the
session's login
role would cover that else branch and this would also exercise the path in
point #1


Regards,
Surya Poondla

^ permalink  raw  reply  [nested|flat] 12+ messages in thread

* Re: Fix races conditions in DropRole() and GrantRole()
  2026-07-04 07:47 Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-09 04:45 ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-09 07:05   ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-10 21:42     ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
@ 2026-07-15 03:37       ` Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-16 16:56         ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  0 siblings, 1 reply; 12+ messages in thread

From: Bertrand Drouvot @ 2026-07-15 03:37 UTC (permalink / raw)
  To: surya poondla <suryapoondla4@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Surya,

On Fri, Jul 10, 2026 at 02:42:26PM -0700, surya poondla wrote:
> Instead we can report the OID and it avoids the re-lookup entirely, e.g.
> 
>        if (!SearchSysCacheExists1(AUTHOID, ObjectIdGetDatum(roleid)))
>            ereport(ERROR,
>                    (errcode(ERRCODE_UNDEFINED_OBJECT),
>                     errmsg("role with OID %u does not exist", roleid)));

Agreed and done in the attached.

> 2. The new s2_check_orphans permutations all use named roles, which go
> through the RoleNameGetOid() (CSTRING) path. None exercise the
> CURRENT_USER/SESSION_USER else-branch that the recheck was added for.
> A permutation like "GRANT g TO CURRENT_USER" with a concurrent drop of the
> session's login
> role would cover that else branch and this would also exercise the path in
> point #1

Test added.

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com

Attachments:

  [text/x-diff] v4-0001-Add-RoleNameGetOid-with-invalidation-based-retry-.patch (13.0K, ../../alcAi0scidMqjO4y@bdtpg/2-v4-0001-Add-RoleNameGetOid-with-invalidation-based-retry-.patch)
  download | inline diff:
From 6754929d365f4414bbc0c45bf447ca86d7536462 Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Mon, 6 Jul 2026 08:28:41 +0000
Subject: [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry
 loop for DropRole()/GrantRole()

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

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

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

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

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

AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Reviewed-by: Surya Poondla <suryapoondla4@gmail.com>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
 src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
 src/include/commands/user.h |   9 ++
 2 files changed, 193 insertions(+), 64 deletions(-)
  95.5% src/backend/commands/
   4.4% src/include/commands/

diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
 #include "miscadmin.h"
 #include "port/pg_bitutils.h"
 #include "storage/lmgr.h"
+#include "storage/sinval.h"
 #include "utils/acl.h"
 #include "utils/builtins.h"
 #include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
 								  bool revoke_admin_option_only,
 								  DropBehavior behavior);
 static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+										Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+										 Oid oldroleid, void *callback_arg);
 
 
 /* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
 }
 
 
+/*
+ * RoleNameGetOid
+ *		Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+			   RoleNameGetOidCallback callback, void *callback_arg)
+{
+	uint64		inval_count;
+	Oid			roleid;
+	Oid			oldroleid = InvalidOid;
+	bool		retry = false;
+
+	for (;;)
+	{
+		/*
+		 * Remember the current invalidation count so we can detect concurrent
+		 * DDL after locking.
+		 */
+		inval_count = SharedInvalidMessageCounter;
+
+		/* Look up the role name */
+		roleid = get_role_oid(rolename, true);
+
+		if (!OidIsValid(roleid))
+		{
+			if (retry)
+				UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+			if (!missing_ok)
+				ereport(ERROR,
+						(errcode(ERRCODE_UNDEFINED_OBJECT),
+						 errmsg("role \"%s\" does not exist", rolename)));
+			return InvalidOid;
+		}
+
+		/*
+		 * Invoke caller-supplied callback before locking. This is a good
+		 * place to check permissions: we haven't taken the lock yet, but we
+		 * know the OID we intend to lock. If concurrent DDL changes things,
+		 * the callback will be invoked again on the next iteration.
+		 */
+		if (callback)
+			callback(rolename, roleid, oldroleid, callback_arg);
+
+		/*
+		 * If upon retry we get back the same OID, the invalidation messages
+		 * did not change the final answer. So we're done.
+		 *
+		 * If we got a different OID, we've locked the role that used to have
+		 * this name rather than the one that does now. Release the old lock.
+		 */
+		if (retry)
+		{
+			if (roleid == oldroleid)
+				break;
+			UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+		}
+
+		/* Lock the role */
+		LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+		/* If no invalidation messages were processed, we're done */
+		if (inval_count == SharedInvalidMessageCounter)
+			break;
+
+		/* Something may have changed, retry */
+		retry = true;
+		oldroleid = roleid;
+	}
+
+	return roleid;
+}
+
+
 /*
  * CREATE ROLE
  */
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
 }
 
 
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+							Oid oldroleid, void *callback_arg)
+{
+	HeapTuple	tuple;
+	Form_pg_authid roleform;
+
+	if (roleid == GetUserId())
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_IN_USE),
+				 errmsg("current user cannot be dropped")));
+	if (roleid == GetOuterUserId())
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_IN_USE),
+				 errmsg("current user cannot be dropped")));
+	if (roleid == GetSessionUserId())
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_IN_USE),
+				 errmsg("session user cannot be dropped")));
+
+	tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+	if (!HeapTupleIsValid(tuple))
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("role \"%s\" does not exist", rolename)));
+
+	roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+	/*
+	 * For safety's sake, we allow createrole holders to drop ordinary roles
+	 * but not superuser roles, and only if they also have ADMIN OPTION.
+	 */
+	if (roleform->rolsuper && !superuser())
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("permission denied to drop role"),
+				 errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+						   "SUPERUSER", "SUPERUSER")));
+	if (!is_admin_of_role(GetUserId(), roleid))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("permission denied to drop role"),
+				 errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+						   "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+	ReleaseSysCache(tuple);
+}
+
+
 /*
  * DROP ROLE
  */
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
 	{
 		RoleSpec   *rolspec = lfirst(item);
 		char	   *role;
-		HeapTuple	tuple,
-					tmp_tuple;
-		Form_pg_authid roleform;
+		HeapTuple	tmp_tuple;
 		ScanKeyData scankey;
 		SysScanDesc sscan;
 		Oid			roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
 					 errmsg("cannot use special role specifier in DROP ROLE")));
 		role = rolspec->rolename;
 
-		tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
-		if (!HeapTupleIsValid(tuple))
-		{
-			if (!stmt->missing_ok)
-			{
-				ereport(ERROR,
-						(errcode(ERRCODE_UNDEFINED_OBJECT),
-						 errmsg("role \"%s\" does not exist", role)));
-			}
-			else
-			{
-				ereport(NOTICE,
-						(errmsg("role \"%s\" does not exist, skipping",
-								role)));
-			}
+		/*
+		 * Use RoleNameGetOid to resolve the name, check permissions, and lock
+		 * the role atomically with a retry loop. This prevents race
+		 * conditions where a concurrent DROP or ALTER commits between name
+		 * resolution and lock acquisition.
+		 */
+		roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+								RoleNameCallbackForDropRole, NULL);
 
+		if (!OidIsValid(roleid))
+		{
+			/* missing_ok case: role doesn't exist */
+			ereport(NOTICE,
+					(errmsg("role \"%s\" does not exist, skipping",
+							role)));
 			continue;
 		}
 
-		roleform = (Form_pg_authid) GETSTRUCT(tuple);
-		roleid = roleform->oid;
-
-		if (roleid == GetUserId())
-			ereport(ERROR,
-					(errcode(ERRCODE_OBJECT_IN_USE),
-					 errmsg("current user cannot be dropped")));
-		if (roleid == GetOuterUserId())
-			ereport(ERROR,
-					(errcode(ERRCODE_OBJECT_IN_USE),
-					 errmsg("current user cannot be dropped")));
-		if (roleid == GetSessionUserId())
-			ereport(ERROR,
-					(errcode(ERRCODE_OBJECT_IN_USE),
-					 errmsg("session user cannot be dropped")));
-
-		/*
-		 * For safety's sake, we allow createrole holders to drop ordinary
-		 * roles but not superuser roles, and only if they also have ADMIN
-		 * OPTION.
-		 */
-		if (roleform->rolsuper && !superuser())
-			ereport(ERROR,
-					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
-					 errmsg("permission denied to drop role"),
-					 errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
-							   "SUPERUSER", "SUPERUSER")));
-		if (!is_admin_of_role(GetUserId(), roleid))
-			ereport(ERROR,
-					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
-					 errmsg("permission denied to drop role"),
-					 errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
-							   "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
 		/* DROP hook for the role being removed */
 		InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
 
-		/* Don't leak the syscache tuple */
-		ReleaseSysCache(tuple);
-
-		/*
-		 * Lock the role, so nobody can add dependencies to her while we drop
-		 * her.  We keep the lock until the end of transaction.
-		 */
-		LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
 		/*
 		 * If there is a pg_auth_members entry that has one of the roles to be
 		 * dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
 	return address;
 }
 
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+							 Oid oldroleid, void *callback_arg)
+{
+	bool		is_grant = *((bool *) callback_arg);
+	Oid			currentUserId = GetUserId();
+
+	check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
 /*
  * GrantRoleStmt
  *
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
 					(errcode(ERRCODE_INVALID_GRANT_OPERATION),
 					 errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
 
-		roleid = get_role_oid(rolename, false);
-		check_role_membership_authorization(currentUserId,
-											roleid, stmt->is_grant);
+		/*
+		 * Use RoleNameGetOid to resolve the name, check permissions, and lock
+		 * the role atomically with a retry loop. This prevents race
+		 * conditions where a concurrent DROP commits between name resolution
+		 * and lock acquisition.
+		 */
+		roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+								RoleNameCallbackForGrantRole, &stmt->is_grant);
 		if (stmt->is_grant)
 			AddRoleMems(currentUserId, rolename, roleid,
 						stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
 extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
 extern PGDLLIMPORT char *createrole_self_grant;
 
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+										Oid oldroleid, void *callback_arg);
+
+extern Oid	RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+						   bool missing_ok,
+						   RoleNameGetOidCallback callback,
+						   void *callback_arg);
+
 /* Hook to check passwords in CreateRole() and AlterRole() */
 typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
 
-- 
2.34.1

  [text/x-diff] v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch (9.6K, ../../alcAi0scidMqjO4y@bdtpg/3-v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch)
  download | inline diff:
From 877204f294ae66d37472035d9ffe4bb3e1a850c0 Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Mon, 6 Jul 2026 08:28:41 +0000
Subject: [PATCH v4 2/2] Protect role resolution in roleSpecsToIds() against
 concurrent DROP

roleSpecsToIds() resolves role names to OIDs without acquiring any lock.
A concurrent DROP ROLE that commits between this resolution and the caller's use
of the OID leaves the caller operating on a stale OID, which can create orphaned
pg_auth_members entries.

Fix this by acquiring AccessShareLock on each resolved role within
roleSpecsToIds(), ensuring the role cannot be dropped while any caller is using
its OID.

The AccessShareLock is held until end of transaction, so an open transaction
that performed GRANT, CREATE ROLE ... ROLE, or REASSIGN OWNED BY will block a
concurrent DROP ROLE on the same role until it commits.

Note that this introduces a potential deadlock between GRANT and DROP ROLE
when both target overlapping roles. The deadlock is detected and one session is
aborted with an error, which is preferable to the pre-patch behavior of silently
creating orphaned catalog entries.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Reported-by: Virender Singla <virender.cse@gmail.com>
Reviewed-by: Surya Poondla <suryapoondla4@gmail.com>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
Discussion: https://postgr.es/m/CAM6Zo8woa62ZFHtMKox6a4jb8qQ%3Dw87R2L0K8347iE-juQL2EA%40mail.gmail.com
---
 src/backend/commands/user.c                   | 20 +++-
 .../expected/role-membership-drop-member.out  | 97 +++++++++++++++++++
 src/test/isolation/isolation_schedule         |  1 +
 .../specs/role-membership-drop-member.spec    | 63 ++++++++++++
 4 files changed, 180 insertions(+), 1 deletion(-)
  11.5% src/backend/commands/
  49.2% src/test/isolation/expected/
  38.6% src/test/isolation/specs/

diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index 5b869e91c17..ab3cfb0b13f 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -1778,6 +1778,8 @@ ReassignOwnedObjects(ReassignOwnedStmt *stmt)
  * roleSpecsToIds
  *
  * Given a list of RoleSpecs, generate a list of role OIDs in the same order.
+ * Each role is locked with AccessShareLock to prevent concurrent DROP ROLE
+ * from removing it between resolution and the caller's catalog update.
  *
  * ROLESPEC_PUBLIC is not allowed.
  */
@@ -1792,7 +1794,23 @@ roleSpecsToIds(List *memberNames)
 		RoleSpec   *rolespec = lfirst_node(RoleSpec, l);
 		Oid			roleid;
 
-		roleid = get_rolespec_oid(rolespec, false);
+		if (rolespec->roletype == ROLESPEC_CSTRING)
+			roleid = RoleNameGetOid(rolespec->rolename,
+									AccessShareLock, false,
+									NULL, NULL);
+		else
+		{
+			roleid = get_rolespec_oid(rolespec, false);
+			LockSharedObject(AuthIdRelationId, roleid, 0,
+							 AccessShareLock);
+
+			/* Recheck that the role still exists after locking. */
+			if (!SearchSysCacheExists1(AUTHOID, ObjectIdGetDatum(roleid)))
+				ereport(ERROR,
+						(errcode(ERRCODE_UNDEFINED_OBJECT),
+						 errmsg("role with OID %u does not exist", roleid)));
+		}
+
 		result = lappend_oid(result, roleid);
 	}
 	return result;
diff --git a/src/test/isolation/expected/role-membership-drop-member.out b/src/test/isolation/expected/role-membership-drop-member.out
new file mode 100644
index 00000000000..7daf48395ca
--- /dev/null
+++ b/src/test/isolation/expected/role-membership-drop-member.out
@@ -0,0 +1,97 @@
+Parsed test spec with 2 sessions
+
+starting permutation: s1_begin s1_grant s2_drop_member s1_commit s2_check_orphans
+step s1_begin: BEGIN;
+step s1_grant: GRANT regress_role_group TO regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+step s2_check_orphans: 
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+
+count
+-----
+    0
+(1 row)
+
+
+starting permutation: s1_begin s1_alter_add s2_drop_member s1_commit s2_check_orphans
+step s1_begin: BEGIN;
+step s1_alter_add: ALTER GROUP regress_role_group ADD USER regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+step s2_check_orphans: 
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+
+count
+-----
+    0
+(1 row)
+
+
+starting permutation: s1_begin s1_create_role s2_drop_member s1_commit s2_check_orphans
+step s1_begin: BEGIN;
+step s1_create_role: CREATE ROLE regress_role_new ROLE regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+step s2_check_orphans: 
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+
+count
+-----
+    0
+(1 row)
+
+
+starting permutation: s1_begin s1_drop_owned s2_drop_member s1_commit
+step s1_begin: BEGIN;
+step s1_drop_owned: DROP OWNED BY regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+
+starting permutation: s1_begin s1_reassign_owned s2_drop_member s1_commit
+step s1_begin: BEGIN;
+step s1_reassign_owned: REASSIGN OWNED BY regress_role_member TO regress_role_group;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+
+starting permutation: s1_begin s1_set_role s1_grant_cu s2_drop_member_cu s1_commit s1_reset s2_check_orphans
+step s1_begin: BEGIN;
+step s1_set_role: SET ROLE regress_role_member_cu;
+step s1_grant_cu: GRANT regress_role_group_cu TO CURRENT_USER;
+step s2_drop_member_cu: DROP ROLE regress_role_member_cu; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member_cu: <... completed>
+step s1_reset: RESET ROLE;
+step s2_check_orphans: 
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+
+count
+-----
+    0
+(1 row)
+
diff --git a/src/test/isolation/isolation_schedule b/src/test/isolation/isolation_schedule
index b8ebe92553c..8fb8b52b77f 100644
--- a/src/test/isolation/isolation_schedule
+++ b/src/test/isolation/isolation_schedule
@@ -128,3 +128,4 @@ test: matview-write-skew
 test: lock-nowait
 test: for-portion-of
 test: ddl-dependency-locking
+test: role-membership-drop-member
diff --git a/src/test/isolation/specs/role-membership-drop-member.spec b/src/test/isolation/specs/role-membership-drop-member.spec
new file mode 100644
index 00000000000..054326ac535
--- /dev/null
+++ b/src/test/isolation/specs/role-membership-drop-member.spec
@@ -0,0 +1,63 @@
+# Test that role membership commands properly lock the grantee/member
+# role to prevent concurrent DROP ROLE from creating orphaned pg_auth_members
+# entries, or from operating on a stale OID.
+
+setup
+{
+	CREATE ROLE regress_role_group;
+	CREATE ROLE regress_role_member;
+	CREATE ROLE regress_role_group_cu;
+	CREATE ROLE regress_role_member_cu;
+	GRANT regress_role_group_cu TO regress_role_member_cu WITH ADMIN OPTION;
+}
+
+teardown
+{
+	DROP ROLE IF EXISTS regress_role_group;
+	DROP ROLE IF EXISTS regress_role_member;
+	DROP ROLE IF EXISTS regress_role_new;
+	DROP ROLE IF EXISTS regress_role_member_cu;
+	DROP ROLE IF EXISTS regress_role_group_cu;
+}
+
+session s1
+step s1_begin		{ BEGIN; }
+step s1_grant		{ GRANT regress_role_group TO regress_role_member; }
+step s1_alter_add	{ ALTER GROUP regress_role_group ADD USER regress_role_member; }
+step s1_create_role	{ CREATE ROLE regress_role_new ROLE regress_role_member; }
+step s1_drop_owned	{ DROP OWNED BY regress_role_member; }
+step s1_reassign_owned	{ REASSIGN OWNED BY regress_role_member TO regress_role_group; }
+step s1_set_role	{ SET ROLE regress_role_member_cu; }
+step s1_grant_cu	{ GRANT regress_role_group_cu TO CURRENT_USER; }
+step s1_commit		{ COMMIT; }
+step s1_reset		{ RESET ROLE; }
+
+session s2
+step s2_drop_member	{ DROP ROLE regress_role_member; }
+step s2_drop_member_cu	{ DROP ROLE regress_role_member_cu; }
+step s2_check_orphans	{
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+}
+
+# GRANT role TO member and concurrent DROP of the member
+permutation s1_begin s1_grant s2_drop_member s1_commit s2_check_orphans
+
+# ALTER GROUP ADD USER and concurrent DROP of the member
+permutation s1_begin s1_alter_add s2_drop_member s1_commit s2_check_orphans
+
+# CREATE ROLE ... ROLE member and concurrent DROP of the member
+permutation s1_begin s1_create_role s2_drop_member s1_commit s2_check_orphans
+
+# DROP OWNED BY role and concurrent DROP of the role
+permutation s1_begin s1_drop_owned s2_drop_member s1_commit
+
+# REASSIGN OWNED BY role and concurrent DROP of the role
+permutation s1_begin s1_reassign_owned s2_drop_member s1_commit
+
+# GRANT role TO CURRENT_USER and concurrent DROP of the current user
+permutation s1_begin s1_set_role s1_grant_cu s2_drop_member_cu s1_commit s1_reset s2_check_orphans
-- 
2.34.1

^ permalink  raw  reply  [nested|flat] 12+ messages in thread

* Re: Fix races conditions in DropRole() and GrantRole()
  2026-07-04 07:47 Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-09 04:45 ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-09 07:05   ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-10 21:42     ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-15 03:37       ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
@ 2026-07-16 16:56         ` surya poondla <suryapoondla4@gmail.com>
  2026-07-20 21:20           ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  0 siblings, 1 reply; 12+ messages in thread

From: surya poondla @ 2026-07-16 16:56 UTC (permalink / raw)
  To: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Bertrand,

I reviewed the v4 patch, the OID-based error message and the CURRENT_USER
permutation both look good.

One minor note on the new permutation: it grants first and drops second, so
s1 already holds AccessShareLock on the member when s2's DROP arrives.
That exercises the lock/no-orphan path, but the DROP just waits and the
recheck
never fails, so the "role with OID %u does not exist" branch itself still
isn't covered.
If we reorder like the DROP commits before the GRANT i.e (s1 SET ROLE,
s2 DROP, then s1 GRANT ... TO CURRENT_USER) this would exercise that error
path.
It is not essential, because the code there is now straightforward.

Otherwise this looks ready to me.

Regards,
Surya Poondla

^ permalink  raw  reply  [nested|flat] 12+ messages in thread

* Re: Fix races conditions in DropRole() and GrantRole()
  2026-07-04 07:47 Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-09 04:45 ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-09 07:05   ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-10 21:42     ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-15 03:37       ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-16 16:56         ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
@ 2026-07-20 21:20           ` surya poondla <suryapoondla4@gmail.com>
  2026-07-21 09:46             ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  0 siblings, 1 reply; 12+ messages in thread

From: surya poondla @ 2026-07-20 21:20 UTC (permalink / raw)
  To: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Bertrand,

The v4 patch looks good to me.
You can create a commitfest entry and we can take it from there.

Regards,
Surya Poondla

^ permalink  raw  reply  [nested|flat] 12+ messages in thread

* Re: Fix races conditions in DropRole() and GrantRole()
  2026-07-04 07:47 Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-09 04:45 ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-09 07:05   ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-10 21:42     ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-15 03:37       ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-16 16:56         ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-20 21:20           ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
@ 2026-07-21 09:46             ` Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-21 17:26               ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  0 siblings, 1 reply; 12+ messages in thread

From: Bertrand Drouvot @ 2026-07-21 09:46 UTC (permalink / raw)
  To: surya poondla <suryapoondla4@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Surya,

On Mon, Jul 20, 2026 at 02:20:59PM -0700, surya poondla wrote:
> Hi Bertrand,
> 
> The v4 patch looks good to me.

Thanks for the review!

> You can create a commitfest entry and we can take it from there.

I've already created one [1].

[1]: https://commitfest.postgresql.org/patch/6985/

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com





^ permalink  raw  reply  [nested|flat] 12+ messages in thread

* Re: Fix races conditions in DropRole() and GrantRole()
  2026-07-04 07:47 Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-09 04:45 ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-09 07:05   ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-10 21:42     ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-15 03:37       ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-16 16:56         ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-20 21:20           ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-21 09:46             ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
@ 2026-07-21 17:26               ` surya poondla <suryapoondla4@gmail.com>
  2026-08-04 06:41                 ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  0 siblings, 1 reply; 12+ messages in thread

From: surya poondla @ 2026-07-21 17:26 UTC (permalink / raw)
  To: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Bertrand,

Thank you for sharing the commitfest entry.

The v4 patch looks all good. I hope the patch gets pushed soon.

Regards,
Surya Poondla

^ permalink  raw  reply  [nested|flat] 12+ messages in thread

* Re: Fix races conditions in DropRole() and GrantRole()
  2026-07-04 07:47 Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-09 04:45 ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-09 07:05   ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-10 21:42     ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-15 03:37       ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-16 16:56         ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-20 21:20           ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-21 09:46             ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-21 17:26               ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
@ 2026-08-04 06:41                 ` Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-08-05 17:53                   ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  0 siblings, 1 reply; 12+ messages in thread

From: Bertrand Drouvot @ 2026-08-04 06:41 UTC (permalink / raw)
  To: surya poondla <suryapoondla4@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Surya,

On Tue, Jul 21, 2026 at 10:26:01AM -0700, surya poondla wrote:
> Hi Bertrand,
> 
> Thank you for sharing the commitfest entry.
> 
> The v4 patch looks all good. I hope the patch gets pushed soon.

Thanks! Attached a mandatory rebase (no major changes, just the new test position
in isolation_schedule).

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com

Attachments:

  [text/x-diff] v5-0001-Add-RoleNameGetOid-with-invalidation-based-retry-.patch (13.0K, ../../anGJmG9aUAGUb0R%2F@bdtpg/2-v5-0001-Add-RoleNameGetOid-with-invalidation-based-retry-.patch)
  download | inline diff:
From d7be97d86e025292531ebe77222036638c8966ee Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Mon, 6 Jul 2026 08:28:41 +0000
Subject: [PATCH v5 1/2] Add RoleNameGetOid() with invalidation-based retry
 loop for DropRole()/GrantRole()

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

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

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

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

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

AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Reviewed-by: Surya Poondla <suryapoondla4@gmail.com>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
 src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
 src/include/commands/user.h |   9 ++
 2 files changed, 193 insertions(+), 64 deletions(-)
  95.5% src/backend/commands/
   4.4% src/include/commands/

diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
 #include "miscadmin.h"
 #include "port/pg_bitutils.h"
 #include "storage/lmgr.h"
+#include "storage/sinval.h"
 #include "utils/acl.h"
 #include "utils/builtins.h"
 #include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
 								  bool revoke_admin_option_only,
 								  DropBehavior behavior);
 static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+										Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+										 Oid oldroleid, void *callback_arg);
 
 
 /* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
 }
 
 
+/*
+ * RoleNameGetOid
+ *		Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+			   RoleNameGetOidCallback callback, void *callback_arg)
+{
+	uint64		inval_count;
+	Oid			roleid;
+	Oid			oldroleid = InvalidOid;
+	bool		retry = false;
+
+	for (;;)
+	{
+		/*
+		 * Remember the current invalidation count so we can detect concurrent
+		 * DDL after locking.
+		 */
+		inval_count = SharedInvalidMessageCounter;
+
+		/* Look up the role name */
+		roleid = get_role_oid(rolename, true);
+
+		if (!OidIsValid(roleid))
+		{
+			if (retry)
+				UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+			if (!missing_ok)
+				ereport(ERROR,
+						(errcode(ERRCODE_UNDEFINED_OBJECT),
+						 errmsg("role \"%s\" does not exist", rolename)));
+			return InvalidOid;
+		}
+
+		/*
+		 * Invoke caller-supplied callback before locking. This is a good
+		 * place to check permissions: we haven't taken the lock yet, but we
+		 * know the OID we intend to lock. If concurrent DDL changes things,
+		 * the callback will be invoked again on the next iteration.
+		 */
+		if (callback)
+			callback(rolename, roleid, oldroleid, callback_arg);
+
+		/*
+		 * If upon retry we get back the same OID, the invalidation messages
+		 * did not change the final answer. So we're done.
+		 *
+		 * If we got a different OID, we've locked the role that used to have
+		 * this name rather than the one that does now. Release the old lock.
+		 */
+		if (retry)
+		{
+			if (roleid == oldroleid)
+				break;
+			UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+		}
+
+		/* Lock the role */
+		LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+		/* If no invalidation messages were processed, we're done */
+		if (inval_count == SharedInvalidMessageCounter)
+			break;
+
+		/* Something may have changed, retry */
+		retry = true;
+		oldroleid = roleid;
+	}
+
+	return roleid;
+}
+
+
 /*
  * CREATE ROLE
  */
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
 }
 
 
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+							Oid oldroleid, void *callback_arg)
+{
+	HeapTuple	tuple;
+	Form_pg_authid roleform;
+
+	if (roleid == GetUserId())
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_IN_USE),
+				 errmsg("current user cannot be dropped")));
+	if (roleid == GetOuterUserId())
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_IN_USE),
+				 errmsg("current user cannot be dropped")));
+	if (roleid == GetSessionUserId())
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_IN_USE),
+				 errmsg("session user cannot be dropped")));
+
+	tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+	if (!HeapTupleIsValid(tuple))
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("role \"%s\" does not exist", rolename)));
+
+	roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+	/*
+	 * For safety's sake, we allow createrole holders to drop ordinary roles
+	 * but not superuser roles, and only if they also have ADMIN OPTION.
+	 */
+	if (roleform->rolsuper && !superuser())
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("permission denied to drop role"),
+				 errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+						   "SUPERUSER", "SUPERUSER")));
+	if (!is_admin_of_role(GetUserId(), roleid))
+		ereport(ERROR,
+				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+				 errmsg("permission denied to drop role"),
+				 errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+						   "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+	ReleaseSysCache(tuple);
+}
+
+
 /*
  * DROP ROLE
  */
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
 	{
 		RoleSpec   *rolspec = lfirst(item);
 		char	   *role;
-		HeapTuple	tuple,
-					tmp_tuple;
-		Form_pg_authid roleform;
+		HeapTuple	tmp_tuple;
 		ScanKeyData scankey;
 		SysScanDesc sscan;
 		Oid			roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
 					 errmsg("cannot use special role specifier in DROP ROLE")));
 		role = rolspec->rolename;
 
-		tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
-		if (!HeapTupleIsValid(tuple))
-		{
-			if (!stmt->missing_ok)
-			{
-				ereport(ERROR,
-						(errcode(ERRCODE_UNDEFINED_OBJECT),
-						 errmsg("role \"%s\" does not exist", role)));
-			}
-			else
-			{
-				ereport(NOTICE,
-						(errmsg("role \"%s\" does not exist, skipping",
-								role)));
-			}
+		/*
+		 * Use RoleNameGetOid to resolve the name, check permissions, and lock
+		 * the role atomically with a retry loop. This prevents race
+		 * conditions where a concurrent DROP or ALTER commits between name
+		 * resolution and lock acquisition.
+		 */
+		roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+								RoleNameCallbackForDropRole, NULL);
 
+		if (!OidIsValid(roleid))
+		{
+			/* missing_ok case: role doesn't exist */
+			ereport(NOTICE,
+					(errmsg("role \"%s\" does not exist, skipping",
+							role)));
 			continue;
 		}
 
-		roleform = (Form_pg_authid) GETSTRUCT(tuple);
-		roleid = roleform->oid;
-
-		if (roleid == GetUserId())
-			ereport(ERROR,
-					(errcode(ERRCODE_OBJECT_IN_USE),
-					 errmsg("current user cannot be dropped")));
-		if (roleid == GetOuterUserId())
-			ereport(ERROR,
-					(errcode(ERRCODE_OBJECT_IN_USE),
-					 errmsg("current user cannot be dropped")));
-		if (roleid == GetSessionUserId())
-			ereport(ERROR,
-					(errcode(ERRCODE_OBJECT_IN_USE),
-					 errmsg("session user cannot be dropped")));
-
-		/*
-		 * For safety's sake, we allow createrole holders to drop ordinary
-		 * roles but not superuser roles, and only if they also have ADMIN
-		 * OPTION.
-		 */
-		if (roleform->rolsuper && !superuser())
-			ereport(ERROR,
-					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
-					 errmsg("permission denied to drop role"),
-					 errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
-							   "SUPERUSER", "SUPERUSER")));
-		if (!is_admin_of_role(GetUserId(), roleid))
-			ereport(ERROR,
-					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
-					 errmsg("permission denied to drop role"),
-					 errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
-							   "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
 		/* DROP hook for the role being removed */
 		InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
 
-		/* Don't leak the syscache tuple */
-		ReleaseSysCache(tuple);
-
-		/*
-		 * Lock the role, so nobody can add dependencies to her while we drop
-		 * her.  We keep the lock until the end of transaction.
-		 */
-		LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
 		/*
 		 * If there is a pg_auth_members entry that has one of the roles to be
 		 * dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
 	return address;
 }
 
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+							 Oid oldroleid, void *callback_arg)
+{
+	bool		is_grant = *((bool *) callback_arg);
+	Oid			currentUserId = GetUserId();
+
+	check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
 /*
  * GrantRoleStmt
  *
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
 					(errcode(ERRCODE_INVALID_GRANT_OPERATION),
 					 errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
 
-		roleid = get_role_oid(rolename, false);
-		check_role_membership_authorization(currentUserId,
-											roleid, stmt->is_grant);
+		/*
+		 * Use RoleNameGetOid to resolve the name, check permissions, and lock
+		 * the role atomically with a retry loop. This prevents race
+		 * conditions where a concurrent DROP commits between name resolution
+		 * and lock acquisition.
+		 */
+		roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+								RoleNameCallbackForGrantRole, &stmt->is_grant);
 		if (stmt->is_grant)
 			AddRoleMems(currentUserId, rolename, roleid,
 						stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
 extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
 extern PGDLLIMPORT char *createrole_self_grant;
 
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+										Oid oldroleid, void *callback_arg);
+
+extern Oid	RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+						   bool missing_ok,
+						   RoleNameGetOidCallback callback,
+						   void *callback_arg);
+
 /* Hook to check passwords in CreateRole() and AlterRole() */
 typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
 
-- 
2.34.1

  [text/x-diff] v5-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch (9.6K, ../../anGJmG9aUAGUb0R%2F@bdtpg/3-v5-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch)
  download | inline diff:
From 30f8ea56beb738a5ae524039c0177c8339c0e156 Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Mon, 6 Jul 2026 08:28:41 +0000
Subject: [PATCH v5 2/2] Protect role resolution in roleSpecsToIds() against
 concurrent DROP

roleSpecsToIds() resolves role names to OIDs without acquiring any lock.
A concurrent DROP ROLE that commits between this resolution and the caller's use
of the OID leaves the caller operating on a stale OID, which can create orphaned
pg_auth_members entries.

Fix this by acquiring AccessShareLock on each resolved role within
roleSpecsToIds(), ensuring the role cannot be dropped while any caller is using
its OID.

The AccessShareLock is held until end of transaction, so an open transaction
that performed GRANT, CREATE ROLE ... ROLE, or REASSIGN OWNED BY will block a
concurrent DROP ROLE on the same role until it commits.

Note that this introduces a potential deadlock between GRANT and DROP ROLE
when both target overlapping roles. The deadlock is detected and one session is
aborted with an error, which is preferable to the pre-patch behavior of silently
creating orphaned catalog entries.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Reported-by: Virender Singla <virender.cse@gmail.com>
Reviewed-by: Surya Poondla <suryapoondla4@gmail.com>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
Discussion: https://postgr.es/m/CAM6Zo8woa62ZFHtMKox6a4jb8qQ%3Dw87R2L0K8347iE-juQL2EA%40mail.gmail.com
---
 src/backend/commands/user.c                   | 20 +++-
 .../expected/role-membership-drop-member.out  | 97 +++++++++++++++++++
 src/test/isolation/isolation_schedule         |  1 +
 .../specs/role-membership-drop-member.spec    | 63 ++++++++++++
 4 files changed, 180 insertions(+), 1 deletion(-)
  11.5% src/backend/commands/
  49.2% src/test/isolation/expected/
  38.6% src/test/isolation/specs/

diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index 5b869e91c17..ab3cfb0b13f 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -1778,6 +1778,8 @@ ReassignOwnedObjects(ReassignOwnedStmt *stmt)
  * roleSpecsToIds
  *
  * Given a list of RoleSpecs, generate a list of role OIDs in the same order.
+ * Each role is locked with AccessShareLock to prevent concurrent DROP ROLE
+ * from removing it between resolution and the caller's catalog update.
  *
  * ROLESPEC_PUBLIC is not allowed.
  */
@@ -1792,7 +1794,23 @@ roleSpecsToIds(List *memberNames)
 		RoleSpec   *rolespec = lfirst_node(RoleSpec, l);
 		Oid			roleid;
 
-		roleid = get_rolespec_oid(rolespec, false);
+		if (rolespec->roletype == ROLESPEC_CSTRING)
+			roleid = RoleNameGetOid(rolespec->rolename,
+									AccessShareLock, false,
+									NULL, NULL);
+		else
+		{
+			roleid = get_rolespec_oid(rolespec, false);
+			LockSharedObject(AuthIdRelationId, roleid, 0,
+							 AccessShareLock);
+
+			/* Recheck that the role still exists after locking. */
+			if (!SearchSysCacheExists1(AUTHOID, ObjectIdGetDatum(roleid)))
+				ereport(ERROR,
+						(errcode(ERRCODE_UNDEFINED_OBJECT),
+						 errmsg("role with OID %u does not exist", roleid)));
+		}
+
 		result = lappend_oid(result, roleid);
 	}
 	return result;
diff --git a/src/test/isolation/expected/role-membership-drop-member.out b/src/test/isolation/expected/role-membership-drop-member.out
new file mode 100644
index 00000000000..7daf48395ca
--- /dev/null
+++ b/src/test/isolation/expected/role-membership-drop-member.out
@@ -0,0 +1,97 @@
+Parsed test spec with 2 sessions
+
+starting permutation: s1_begin s1_grant s2_drop_member s1_commit s2_check_orphans
+step s1_begin: BEGIN;
+step s1_grant: GRANT regress_role_group TO regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+step s2_check_orphans: 
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+
+count
+-----
+    0
+(1 row)
+
+
+starting permutation: s1_begin s1_alter_add s2_drop_member s1_commit s2_check_orphans
+step s1_begin: BEGIN;
+step s1_alter_add: ALTER GROUP regress_role_group ADD USER regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+step s2_check_orphans: 
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+
+count
+-----
+    0
+(1 row)
+
+
+starting permutation: s1_begin s1_create_role s2_drop_member s1_commit s2_check_orphans
+step s1_begin: BEGIN;
+step s1_create_role: CREATE ROLE regress_role_new ROLE regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+step s2_check_orphans: 
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+
+count
+-----
+    0
+(1 row)
+
+
+starting permutation: s1_begin s1_drop_owned s2_drop_member s1_commit
+step s1_begin: BEGIN;
+step s1_drop_owned: DROP OWNED BY regress_role_member;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+
+starting permutation: s1_begin s1_reassign_owned s2_drop_member s1_commit
+step s1_begin: BEGIN;
+step s1_reassign_owned: REASSIGN OWNED BY regress_role_member TO regress_role_group;
+step s2_drop_member: DROP ROLE regress_role_member; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member: <... completed>
+
+starting permutation: s1_begin s1_set_role s1_grant_cu s2_drop_member_cu s1_commit s1_reset s2_check_orphans
+step s1_begin: BEGIN;
+step s1_set_role: SET ROLE regress_role_member_cu;
+step s1_grant_cu: GRANT regress_role_group_cu TO CURRENT_USER;
+step s2_drop_member_cu: DROP ROLE regress_role_member_cu; <waiting ...>
+step s1_commit: COMMIT;
+step s2_drop_member_cu: <... completed>
+step s1_reset: RESET ROLE;
+step s2_check_orphans: 
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+
+count
+-----
+    0
+(1 row)
+
diff --git a/src/test/isolation/isolation_schedule b/src/test/isolation/isolation_schedule
index df8ce44ede6..63423eb0aed 100644
--- a/src/test/isolation/isolation_schedule
+++ b/src/test/isolation/isolation_schedule
@@ -130,3 +130,4 @@ test: for-portion-of
 test: ddl-dependency-locking
 test: pub-concurrent-drop
 test: drop-owned-grant
+test: role-membership-drop-member
diff --git a/src/test/isolation/specs/role-membership-drop-member.spec b/src/test/isolation/specs/role-membership-drop-member.spec
new file mode 100644
index 00000000000..054326ac535
--- /dev/null
+++ b/src/test/isolation/specs/role-membership-drop-member.spec
@@ -0,0 +1,63 @@
+# Test that role membership commands properly lock the grantee/member
+# role to prevent concurrent DROP ROLE from creating orphaned pg_auth_members
+# entries, or from operating on a stale OID.
+
+setup
+{
+	CREATE ROLE regress_role_group;
+	CREATE ROLE regress_role_member;
+	CREATE ROLE regress_role_group_cu;
+	CREATE ROLE regress_role_member_cu;
+	GRANT regress_role_group_cu TO regress_role_member_cu WITH ADMIN OPTION;
+}
+
+teardown
+{
+	DROP ROLE IF EXISTS regress_role_group;
+	DROP ROLE IF EXISTS regress_role_member;
+	DROP ROLE IF EXISTS regress_role_new;
+	DROP ROLE IF EXISTS regress_role_member_cu;
+	DROP ROLE IF EXISTS regress_role_group_cu;
+}
+
+session s1
+step s1_begin		{ BEGIN; }
+step s1_grant		{ GRANT regress_role_group TO regress_role_member; }
+step s1_alter_add	{ ALTER GROUP regress_role_group ADD USER regress_role_member; }
+step s1_create_role	{ CREATE ROLE regress_role_new ROLE regress_role_member; }
+step s1_drop_owned	{ DROP OWNED BY regress_role_member; }
+step s1_reassign_owned	{ REASSIGN OWNED BY regress_role_member TO regress_role_group; }
+step s1_set_role	{ SET ROLE regress_role_member_cu; }
+step s1_grant_cu	{ GRANT regress_role_group_cu TO CURRENT_USER; }
+step s1_commit		{ COMMIT; }
+step s1_reset		{ RESET ROLE; }
+
+session s2
+step s2_drop_member	{ DROP ROLE regress_role_member; }
+step s2_drop_member_cu	{ DROP ROLE regress_role_member_cu; }
+step s2_check_orphans	{
+	SELECT count(*)
+	FROM pg_auth_members m
+	LEFT JOIN pg_authid ra ON m.roleid  = ra.oid
+	LEFT JOIN pg_authid me ON m.member  = me.oid
+	LEFT JOIN pg_authid gr ON m.grantor = gr.oid
+	WHERE ra.oid IS NULL OR me.oid IS NULL OR gr.oid IS NULL;
+}
+
+# GRANT role TO member and concurrent DROP of the member
+permutation s1_begin s1_grant s2_drop_member s1_commit s2_check_orphans
+
+# ALTER GROUP ADD USER and concurrent DROP of the member
+permutation s1_begin s1_alter_add s2_drop_member s1_commit s2_check_orphans
+
+# CREATE ROLE ... ROLE member and concurrent DROP of the member
+permutation s1_begin s1_create_role s2_drop_member s1_commit s2_check_orphans
+
+# DROP OWNED BY role and concurrent DROP of the role
+permutation s1_begin s1_drop_owned s2_drop_member s1_commit
+
+# REASSIGN OWNED BY role and concurrent DROP of the role
+permutation s1_begin s1_reassign_owned s2_drop_member s1_commit
+
+# GRANT role TO CURRENT_USER and concurrent DROP of the current user
+permutation s1_begin s1_set_role s1_grant_cu s2_drop_member_cu s1_commit s1_reset s2_check_orphans
-- 
2.34.1

^ permalink  raw  reply  [nested|flat] 12+ messages in thread

* Re: Fix races conditions in DropRole() and GrantRole()
  2026-07-04 07:47 Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-09 04:45 ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-09 07:05   ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-10 21:42     ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-15 03:37       ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-16 16:56         ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-20 21:20           ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-07-21 09:46             ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
  2026-07-21 17:26               ` Re: Fix races conditions in DropRole() and GrantRole() surya poondla <suryapoondla4@gmail.com>
  2026-08-04 06:41                 ` Re: Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
@ 2026-08-05 17:53                   ` surya poondla <suryapoondla4@gmail.com>
  0 siblings, 0 replies; 12+ messages in thread

From: surya poondla @ 2026-08-05 17:53 UTC (permalink / raw)
  To: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Bertrand,

The v5 patches look good to me.

Regards,
Surya Poondla

^ permalink  raw  reply  [nested|flat] 12+ messages in thread


end of thread, other threads:[~2026-08-05 17:53 UTC | newest]

Thread overview: 12+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-07-04 07:47 Fix races conditions in DropRole() and GrantRole() Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
2026-07-06 13:22 ` Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
2026-07-09 04:45 ` surya poondla <suryapoondla4@gmail.com>
2026-07-09 07:05   ` Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
2026-07-10 21:42     ` surya poondla <suryapoondla4@gmail.com>
2026-07-15 03:37       ` Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
2026-07-16 16:56         ` surya poondla <suryapoondla4@gmail.com>
2026-07-20 21:20           ` surya poondla <suryapoondla4@gmail.com>
2026-07-21 09:46             ` Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
2026-07-21 17:26               ` surya poondla <suryapoondla4@gmail.com>
2026-08-04 06:41                 ` Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
2026-08-05 17:53                   ` surya poondla <suryapoondla4@gmail.com>

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