agora inbox for [email protected]
help / color / mirror / Atom feed[PATCH v46 4/7] rename cluster.c/h to repack.c/h
165+ messages / 2 participants
[nested] [flat]
* [PATCH v46 4/7] rename cluster.c/h to repack.c/h
@ 2026-03-27 15:40 Álvaro Herrera <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Álvaro Herrera @ 2026-03-27 15:40 UTC (permalink / raw)
---
src/backend/commands/Makefile | 2 +-
src/backend/commands/matview.c | 2 +-
src/backend/commands/meson.build | 2 +-
src/backend/commands/{cluster.c => repack.c} | 6 +++---
src/backend/commands/repack_worker.c | 2 +-
src/backend/commands/tablecmds.c | 2 +-
src/backend/commands/vacuum.c | 2 +-
src/backend/libpq/pqmq.c | 2 +-
src/backend/postmaster/bgworker.c | 2 +-
src/backend/replication/logical/decode.c | 2 +-
src/backend/storage/ipc/procsignal.c | 2 +-
src/backend/tcop/postgres.c | 2 +-
src/backend/tcop/utility.c | 2 +-
src/include/commands/{cluster.h => repack.h} | 12 ++++++------
14 files changed, 21 insertions(+), 21 deletions(-)
rename src/backend/commands/{cluster.c => repack.c} (99%)
rename src/include/commands/{cluster.h => repack.h} (92%)
diff --git a/src/backend/commands/Makefile b/src/backend/commands/Makefile
index 6926bc44818..5b9d084977e 100644
--- a/src/backend/commands/Makefile
+++ b/src/backend/commands/Makefile
@@ -18,7 +18,6 @@ OBJS = \
amcmds.o \
analyze.o \
async.o \
- cluster.o \
collationcmds.o \
comment.o \
constraint.o \
@@ -51,6 +50,7 @@ OBJS = \
proclang.o \
propgraphcmds.o \
publicationcmds.o \
+ repack.o \
repack_worker.o \
schemacmds.o \
seclabel.o \
diff --git a/src/backend/commands/matview.c b/src/backend/commands/matview.c
index 539969d6eef..146a65dae8d 100644
--- a/src/backend/commands/matview.c
+++ b/src/backend/commands/matview.c
@@ -24,8 +24,8 @@
#include "catalog/namespace.h"
#include "catalog/pg_am.h"
#include "catalog/pg_opclass.h"
-#include "commands/cluster.h"
#include "commands/matview.h"
+#include "commands/repack.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "executor/executor.h"
diff --git a/src/backend/commands/meson.build b/src/backend/commands/meson.build
index 4a0e6f0002b..9f258d566eb 100644
--- a/src/backend/commands/meson.build
+++ b/src/backend/commands/meson.build
@@ -6,7 +6,6 @@ backend_sources += files(
'amcmds.c',
'analyze.c',
'async.c',
- 'cluster.c',
'collationcmds.c',
'comment.c',
'constraint.c',
@@ -39,6 +38,7 @@ backend_sources += files(
'proclang.c',
'propgraphcmds.c',
'publicationcmds.c',
+ 'repack.c',
'repack_worker.c',
'schemacmds.c',
'seclabel.c',
diff --git a/src/backend/commands/cluster.c b/src/backend/commands/repack.c
similarity index 99%
rename from src/backend/commands/cluster.c
rename to src/backend/commands/repack.c
index 33083a2b030..a58277bb6c1 100644
--- a/src/backend/commands/cluster.c
+++ b/src/backend/commands/repack.c
@@ -1,6 +1,6 @@
/*-------------------------------------------------------------------------
*
- * cluster.c
+ * repack.c
* REPACK a table; formerly known as CLUSTER. VACUUM FULL also uses
* parts of this code.
*
@@ -26,7 +26,7 @@
*
*
* IDENTIFICATION
- * src/backend/commands/cluster.c
+ * src/backend/commands/repack.c
*
*-------------------------------------------------------------------------
*/
@@ -52,9 +52,9 @@
#include "catalog/pg_control.h"
#include "catalog/pg_inherits.h"
#include "catalog/toasting.h"
-#include "commands/cluster.h"
#include "commands/defrem.h"
#include "commands/progress.h"
+#include "commands/repack.h"
#include "commands/repack_internal.h"
#include "commands/tablecmds.h"
#include "commands/vacuum.h"
diff --git a/src/backend/commands/repack_worker.c b/src/backend/commands/repack_worker.c
index 35ab1a25c42..106b2b60441 100644
--- a/src/backend/commands/repack_worker.c
+++ b/src/backend/commands/repack_worker.c
@@ -20,7 +20,7 @@
#include "access/xlog_internal.h"
#include "access/xlogutils.h"
#include "access/xlogwait.h"
-#include "commands/cluster.h"
+#include "commands/repack.h"
#include "commands/repack_internal.h"
#include "libpq/pqmq.h"
#include "replication/snapbuild.h"
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index cc70439627b..e411d84c776 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -57,10 +57,10 @@
#include "catalog/storage.h"
#include "catalog/storage_xlog.h"
#include "catalog/toasting.h"
-#include "commands/cluster.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/event_trigger.h"
+#include "commands/repack.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c
index 201835f30a4..ac41c819f65 100644
--- a/src/backend/commands/vacuum.c
+++ b/src/backend/commands/vacuum.c
@@ -38,9 +38,9 @@
#include "catalog/pg_database.h"
#include "catalog/pg_inherits.h"
#include "commands/async.h"
-#include "commands/cluster.h"
#include "commands/defrem.h"
#include "commands/progress.h"
+#include "commands/repack.h"
#include "commands/vacuum.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
diff --git a/src/backend/libpq/pqmq.c b/src/backend/libpq/pqmq.c
index 1000b7bb06e..cbf6c5a004f 100644
--- a/src/backend/libpq/pqmq.c
+++ b/src/backend/libpq/pqmq.c
@@ -14,7 +14,7 @@
#include "postgres.h"
#include "access/parallel.h"
-#include "commands/cluster.h"
+#include "commands/repack.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/pqmq.h"
diff --git a/src/backend/postmaster/bgworker.c b/src/backend/postmaster/bgworker.c
index cb9c60dfe31..2598ed0b153 100644
--- a/src/backend/postmaster/bgworker.c
+++ b/src/backend/postmaster/bgworker.c
@@ -13,7 +13,7 @@
#include "postgres.h"
#include "access/parallel.h"
-#include "commands/cluster.h"
+#include "commands/repack.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pgstat.h"
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index f172c0b2b40..8a969ddca41 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -33,7 +33,7 @@
#include "access/xlogreader.h"
#include "access/xlogrecord.h"
#include "catalog/pg_control.h"
-#include "commands/cluster.h"
+#include "commands/repack.h"
#include "replication/decode.h"
#include "replication/logical.h"
#include "replication/message.h"
diff --git a/src/backend/storage/ipc/procsignal.c b/src/backend/storage/ipc/procsignal.c
index dd980145ced..f02b9eb8312 100644
--- a/src/backend/storage/ipc/procsignal.c
+++ b/src/backend/storage/ipc/procsignal.c
@@ -19,7 +19,7 @@
#include "access/parallel.h"
#include "commands/async.h"
-#include "commands/cluster.h"
+#include "commands/repack.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "port/pg_bitutils.h"
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 4d253eddfa0..07bf300e044 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -36,10 +36,10 @@
#include "access/xact.h"
#include "catalog/pg_type.h"
#include "commands/async.h"
-#include "commands/cluster.h"
#include "commands/event_trigger.h"
#include "commands/explain_state.h"
#include "commands/prepare.h"
+#include "commands/repack.h"
#include "common/pg_prng.h"
#include "jit/jit.h"
#include "libpq/libpq.h"
diff --git a/src/backend/tcop/utility.c b/src/backend/tcop/utility.c
index 2b609bfc824..5f8c766c4be 100644
--- a/src/backend/tcop/utility.c
+++ b/src/backend/tcop/utility.c
@@ -26,7 +26,6 @@
#include "catalog/toasting.h"
#include "commands/alter.h"
#include "commands/async.h"
-#include "commands/cluster.h"
#include "commands/collationcmds.h"
#include "commands/comment.h"
#include "commands/conversioncmds.h"
@@ -46,6 +45,7 @@
#include "commands/proclang.h"
#include "commands/propgraphcmds.h"
#include "commands/publicationcmds.h"
+#include "commands/repack.h"
#include "commands/schemacmds.h"
#include "commands/seclabel.h"
#include "commands/sequence.h"
diff --git a/src/include/commands/cluster.h b/src/include/commands/repack.h
similarity index 92%
rename from src/include/commands/cluster.h
rename to src/include/commands/repack.h
index 8ed7816e7b4..6b4ebd7fa5d 100644
--- a/src/include/commands/cluster.h
+++ b/src/include/commands/repack.h
@@ -1,17 +1,17 @@
/*-------------------------------------------------------------------------
*
- * cluster.h
- * header file for postgres cluster command stuff
+ * repack.h
+ * header file for the REPACK command
*
* Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
* Portions Copyright (c) 1994-5, Regents of the University of California
*
- * src/include/commands/cluster.h
+ * src/include/commands/repack.h
*
*-------------------------------------------------------------------------
*/
-#ifndef CLUSTER_H
-#define CLUSTER_H
+#ifndef REPACK_H
+#define REPACK_H
#include <signal.h>
@@ -66,4 +66,4 @@ extern void RepackWorkerMain(Datum main_arg);
extern bool IsRepackWorker(void);
-#endif /* CLUSTER_H */
+#endif /* REPACK_H */
--
2.47.3
--mdsv5bdgfjjj6d77
Content-Type: text/x-diff; charset=utf-8
Content-Disposition: attachment;
filename="v46-0005-Fix-a-few-problems-in-index-build-progress-repor.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-04 04:47 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-04 04:47 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
src/backend/commands/user.c | 246 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 191 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..6d8e2fa8813 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,92 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1181,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1263,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1274,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1582,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1681,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--xlWYagR37YwJXkF8--
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--fotX2lJRknAHpfH+
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v4-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by: Surya Poondla <[email protected]>
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--Dvg/WemKV0I3T/Od
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v3-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
* [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole()
@ 2026-07-06 08:28 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 165+ messages in thread
From: Bertrand Drouvot @ 2026-07-06 08:28 UTC (permalink / raw)
DropRole() and GrantRole() resolve the role name to an OID before acquiring
LockSharedObject() on the role. A concurrent session that commits a DROP ROLE
between the read and the lock acquisition leaves the first session acting on a
stale OID.
This commit fixes the races by using the same approach as RangeVarGetRelidExtended():
It encapsulates name resolution, permission checking (via a caller-supplied callback),
and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter.
If invalidation messages arrive between name resolution and locking, indicating
concurrent DDL, the function retries.
The lock is kept across retries and only released if the name resolves to a
different OID on the next iteration.
Two callbacks are provided:
- RoleNameCallbackForDropRole(): checks current/session user, superuser attribute,
and ADMIN OPTION privilege before locking. This is similar to what DropRole() is
currently doing before LockSharedObject().
- RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to
verify the current user can grant/revoke membership. This is similar to what GrantRole()
is currently doing before calling AddRoleMems()/DelRoleMems().
DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock
levels.
AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the
pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/aki6fMNLUx6%2BBR8K%40bdtpg
---
src/backend/commands/user.c | 248 ++++++++++++++++++++++++++----------
src/include/commands/user.h | 9 ++
2 files changed, 193 insertions(+), 64 deletions(-)
95.5% src/backend/commands/
4.4% src/include/commands/
diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
index be11c49f919..5b869e91c17 100644
--- a/src/backend/commands/user.c
+++ b/src/backend/commands/user.c
@@ -34,6 +34,7 @@
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
+#include "storage/sinval.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
@@ -116,6 +117,10 @@ static void plan_recursive_revoke(CatCList *memlist,
bool revoke_admin_option_only,
DropBehavior behavior);
static void InitGrantRoleOptions(GrantRoleOptions *popt);
+static void RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+static void RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
/* Check if current user has createrole privileges */
@@ -126,6 +131,94 @@ have_createrole_privilege(void)
}
+/*
+ * RoleNameGetOid
+ * Given a role name, look up its OID, lock it, and return the OID.
+ *
+ * This follows the same pattern as RangeVarGetRelidExtended():
+ * name resolution, permission check (via callback), and lock acquisition are
+ * performed inside a retry loop. If invalidation messages arrive during the
+ * process (indicating concurrent DDL), we retry to ensure the name still
+ * resolves to the same OID.
+ *
+ * The callback is invoked before locking, giving callers a chance to check
+ * permissions. It receives the current rolename, the resolved OID, the
+ * previous OID (InvalidOid on first iteration), and a caller-supplied arg.
+ * If the callback raises an error, the function aborts without locking.
+ *
+ * If missing_ok is true and the role does not exist, returns InvalidOid.
+ * Otherwise, raises an error.
+ */
+Oid
+RoleNameGetOid(const char *rolename, LOCKMODE lockmode, bool missing_ok,
+ RoleNameGetOidCallback callback, void *callback_arg)
+{
+ uint64 inval_count;
+ Oid roleid;
+ Oid oldroleid = InvalidOid;
+ bool retry = false;
+
+ for (;;)
+ {
+ /*
+ * Remember the current invalidation count so we can detect concurrent
+ * DDL after locking.
+ */
+ inval_count = SharedInvalidMessageCounter;
+
+ /* Look up the role name */
+ roleid = get_role_oid(rolename, true);
+
+ if (!OidIsValid(roleid))
+ {
+ if (retry)
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ if (!missing_ok)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+ return InvalidOid;
+ }
+
+ /*
+ * Invoke caller-supplied callback before locking. This is a good
+ * place to check permissions: we haven't taken the lock yet, but we
+ * know the OID we intend to lock. If concurrent DDL changes things,
+ * the callback will be invoked again on the next iteration.
+ */
+ if (callback)
+ callback(rolename, roleid, oldroleid, callback_arg);
+
+ /*
+ * If upon retry we get back the same OID, the invalidation messages
+ * did not change the final answer. So we're done.
+ *
+ * If we got a different OID, we've locked the role that used to have
+ * this name rather than the one that does now. Release the old lock.
+ */
+ if (retry)
+ {
+ if (roleid == oldroleid)
+ break;
+ UnlockSharedObject(AuthIdRelationId, oldroleid, 0, lockmode);
+ }
+
+ /* Lock the role */
+ LockSharedObject(AuthIdRelationId, roleid, 0, lockmode);
+
+ /* If no invalidation messages were processed, we're done */
+ if (inval_count == SharedInvalidMessageCounter)
+ break;
+
+ /* Something may have changed, retry */
+ retry = true;
+ oldroleid = roleid;
+ }
+
+ return roleid;
+}
+
+
/*
* CREATE ROLE
*/
@@ -1090,6 +1183,59 @@ AlterRoleSet(AlterRoleSetStmt *stmt)
}
+/*
+ * Before acquiring a role lock for DROP ROLE, check that the role is not the
+ * current/session user and that the caller has sufficient privileges to drop it.
+ */
+static void
+RoleNameCallbackForDropRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ HeapTuple tuple;
+ Form_pg_authid roleform;
+
+ if (roleid == GetUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetOuterUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("current user cannot be dropped")));
+ if (roleid == GetSessionUserId())
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_IN_USE),
+ errmsg("session user cannot be dropped")));
+
+ tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
+ if (!HeapTupleIsValid(tuple))
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("role \"%s\" does not exist", rolename)));
+
+ roleform = (Form_pg_authid) GETSTRUCT(tuple);
+
+ /*
+ * For safety's sake, we allow createrole holders to drop ordinary roles
+ * but not superuser roles, and only if they also have ADMIN OPTION.
+ */
+ if (roleform->rolsuper && !superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
+ "SUPERUSER", "SUPERUSER")));
+ if (!is_admin_of_role(GetUserId(), roleid))
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("permission denied to drop role"),
+ errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
+ "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
+
+ ReleaseSysCache(tuple);
+}
+
+
/*
* DROP ROLE
*/
@@ -1119,9 +1265,7 @@ DropRole(DropRoleStmt *stmt)
{
RoleSpec *rolspec = lfirst(item);
char *role;
- HeapTuple tuple,
- tmp_tuple;
- Form_pg_authid roleform;
+ HeapTuple tmp_tuple;
ScanKeyData scankey;
SysScanDesc sscan;
Oid roleid;
@@ -1132,71 +1276,27 @@ DropRole(DropRoleStmt *stmt)
errmsg("cannot use special role specifier in DROP ROLE")));
role = rolspec->rolename;
- tuple = SearchSysCache1(AUTHNAME, PointerGetDatum(role));
- if (!HeapTupleIsValid(tuple))
- {
- if (!stmt->missing_ok)
- {
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("role \"%s\" does not exist", role)));
- }
- else
- {
- ereport(NOTICE,
- (errmsg("role \"%s\" does not exist, skipping",
- role)));
- }
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP or ALTER commits between name
+ * resolution and lock acquisition.
+ */
+ roleid = RoleNameGetOid(role, AccessExclusiveLock, stmt->missing_ok,
+ RoleNameCallbackForDropRole, NULL);
+ if (!OidIsValid(roleid))
+ {
+ /* missing_ok case: role doesn't exist */
+ ereport(NOTICE,
+ (errmsg("role \"%s\" does not exist, skipping",
+ role)));
continue;
}
- roleform = (Form_pg_authid) GETSTRUCT(tuple);
- roleid = roleform->oid;
-
- if (roleid == GetUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetOuterUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("current user cannot be dropped")));
- if (roleid == GetSessionUserId())
- ereport(ERROR,
- (errcode(ERRCODE_OBJECT_IN_USE),
- errmsg("session user cannot be dropped")));
-
- /*
- * For safety's sake, we allow createrole holders to drop ordinary
- * roles but not superuser roles, and only if they also have ADMIN
- * OPTION.
- */
- if (roleform->rolsuper && !superuser())
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute may drop roles with the %s attribute.",
- "SUPERUSER", "SUPERUSER")));
- if (!is_admin_of_role(GetUserId(), roleid))
- ereport(ERROR,
- (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to drop role"),
- errdetail("Only roles with the %s attribute and the %s option on role \"%s\" may drop this role.",
- "CREATEROLE", "ADMIN", NameStr(roleform->rolname))));
-
/* DROP hook for the role being removed */
InvokeObjectDropHook(AuthIdRelationId, roleid, 0);
- /* Don't leak the syscache tuple */
- ReleaseSysCache(tuple);
-
- /*
- * Lock the role, so nobody can add dependencies to her while we drop
- * her. We keep the lock until the end of transaction.
- */
- LockSharedObject(AuthIdRelationId, roleid, 0, AccessExclusiveLock);
-
/*
* If there is a pg_auth_members entry that has one of the roles to be
* dropped as the roleid or member, it should be silently removed, but
@@ -1484,6 +1584,21 @@ RenameRole(const char *oldname, const char *newname)
return address;
}
+/*
+ * Before acquiring a role lock for GRANT/REVOKE, check that the current user
+ * has authorization to grant/revoke membership in the specified role.
+ */
+static void
+RoleNameCallbackForGrantRole(const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg)
+{
+ bool is_grant = *((bool *) callback_arg);
+ Oid currentUserId = GetUserId();
+
+ check_role_membership_authorization(currentUserId, roleid, is_grant);
+}
+
+
/*
* GrantRoleStmt
*
@@ -1568,9 +1683,14 @@ GrantRole(ParseState *pstate, GrantRoleStmt *stmt)
(errcode(ERRCODE_INVALID_GRANT_OPERATION),
errmsg("column names cannot be included in GRANT/REVOKE ROLE")));
- roleid = get_role_oid(rolename, false);
- check_role_membership_authorization(currentUserId,
- roleid, stmt->is_grant);
+ /*
+ * Use RoleNameGetOid to resolve the name, check permissions, and lock
+ * the role atomically with a retry loop. This prevents race
+ * conditions where a concurrent DROP commits between name resolution
+ * and lock acquisition.
+ */
+ roleid = RoleNameGetOid(rolename, ShareUpdateExclusiveLock, false,
+ RoleNameCallbackForGrantRole, &stmt->is_grant);
if (stmt->is_grant)
AddRoleMems(currentUserId, rolename, roleid,
stmt->grantee_roles, grantee_ids,
diff --git a/src/include/commands/user.h b/src/include/commands/user.h
index 97dcb93791b..17263452250 100644
--- a/src/include/commands/user.h
+++ b/src/include/commands/user.h
@@ -21,6 +21,15 @@
extern PGDLLIMPORT int Password_encryption; /* values from enum PasswordType */
extern PGDLLIMPORT char *createrole_self_grant;
+/* Callback for RoleNameGetOid, invoked after name resolution but before locking */
+typedef void (*RoleNameGetOidCallback) (const char *rolename, Oid roleid,
+ Oid oldroleid, void *callback_arg);
+
+extern Oid RoleNameGetOid(const char *rolename, LOCKMODE lockmode,
+ bool missing_ok,
+ RoleNameGetOidCallback callback,
+ void *callback_arg);
+
/* Hook to check passwords in CreateRole() and AlterRole() */
typedef void (*check_password_hook_type) (const char *username, const char *shadow_pass, PasswordType password_type, Datum validuntil_time, bool validuntil_null);
--
2.34.1
--cOHldBwZEf1OqVbN
Content-Type: text/x-diff; charset=us-ascii
Content-Disposition: attachment;
filename="v2-0002-Protect-role-resolution-in-roleSpecsToIds-against.patch"
^ permalink raw reply [nested|flat] 165+ messages in thread
end of thread, other threads:[~2026-07-06 08:28 UTC | newest]
Thread overview: 165+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-03-27 15:40 [PATCH v46 4/7] rename cluster.c/h to repack.c/h Álvaro Herrera <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-04 04:47 [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v4 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v3 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
2026-07-06 08:28 [PATCH v2 1/2] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() Bertrand Drouvot <[email protected]>
This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox