Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.96) (envelope-from ) id 1wfv5p-005mxr-2H for pgsql-hackers@arkaria.postgresql.org; Sat, 04 Jul 2026 07:47:18 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.96) (envelope-from ) id 1wfv5o-009si2-1J for pgsql-hackers@arkaria.postgresql.org; Sat, 04 Jul 2026 07:47:16 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.96) (envelope-from ) id 1wfv5n-009sht-2d for pgsql-hackers@lists.postgresql.org; Sat, 04 Jul 2026 07:47:16 +0000 Received: from mail-wm1-x333.google.com ([2a00:1450:4864:20::333]) by makus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (Exim 4.98.2) (envelope-from ) id 1wfv5l-00000001QeH-0Ayz for pgsql-hackers@lists.postgresql.org; Sat, 04 Jul 2026 07:47:14 +0000 Received: by mail-wm1-x333.google.com with SMTP id 5b1f17b1804b1-493c00f74baso7962105e9.0 for ; Sat, 04 Jul 2026 00:47:12 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20251104; t=1783151230; x=1783756030; darn=lists.postgresql.org; h=content-disposition:mime-version:message-id:subject:to:from:date :from:to:cc:subject:date:message-id:reply-to; bh=rfLKTIsF2yp0nn4cHHBpyKA9FRWZlf1o69r4LXCv+V8=; b=E4/gKIa4Ptp1pAhQfp598wMliikE88Zgb7qo1DDtVPLIcKAQ3r+qZhMLstk0+Lvi7Y nJa8fEDl/eYyBwLPxV/h7m4VeJiSGaFDWIi8bDPSw4dBC3p3CGQLRTR+FHW78Aw0ekJ6 P6vANBrBISNLNq1wOtko5Ru8g8iFzOHr/kM9ono+92u7xOJZxrC1SNMFLKVU4DLo+/2W fkBOtLsx0Asn57uWA4bDu+NQAjZ0unR8grYlhdw1acwyfL4hu7q9sDU6sh7ut4kmw1BQ Gn35r/E6Te5AiOjMmKvzGPlooTA8KD8GoJuUi6Rx2PUhM1EENzw54Ds3aAUwGBBpGAIh VytQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1783151230; x=1783756030; h=content-disposition:mime-version:message-id:subject:to:from:date :x-gm-gg:x-gm-message-state:from:to:cc:subject:date:message-id :reply-to; bh=rfLKTIsF2yp0nn4cHHBpyKA9FRWZlf1o69r4LXCv+V8=; b=BZxcHjUSLtv95F7diKrFjbPMy++nK903pZ1OkYf9IUljc0ra4ueMsg1+/uH7UjxLYn cAUYc4Y8s+cwzvKQnlhAJOMe94X0mybhQHbD0xtNoYyMEvswhoykpgagZmURXEYR4R74 BKcFVWD8RsXJA2sQOUXarSVfSpR17YqMzIlzdSuYfQ//Vt9lIikebi3TyjzmvoTN5V2e 39uTDsGuh1jYnBLfq0+gPFx6Esmr/B/zsrn730W8UIo/jzGnow3+eeMyP/iF+fU9M6vB /bLYOexTe4d6+kLLHZrQ0kLBafA1gltHQj3SoU6k1HIFgzLQIHC2gYbKAoJkAS6sL/r1 LyjA== X-Gm-Message-State: AOJu0Yx+n4F/zVv7MLqyRR0GD9pn9IDtkin6iWgevN0TS3gtPeQ2GbAM giV7Ffv6sSRtp6toqaTlrYQG/R1zkG1Ck8v2pXKXGHuaGoA0oig8mum6zKFj0g== X-Gm-Gg: AfdE7cmsLNH2D7pDNQ/dl9+TKTUeySgkUbxNWAy2eOJqj7N/ZtjWC3ofVU1jCxn/Mey N+6y3xU3uYKV9/uhOqXMc2k8WaGLDt/yizi+gZItxxc/qYCROTfyWIfFyWK2QeMQ23h1Yx9eaPT f6IVD6e0mUSfaRds/R0738YNCBAUjr//5zP93t4vMI8B456ASxz1dyslBoHjqQa59gnNBhMWT6B 3lY++ozIMa2N4P1hQ4IHZt06GQ97y0tagsnpOOBxiazfUz64/4Pt1hD01aJhK02fXGZrjbCPW/s O0Dj2UM29ub0ne03lkvdgADcUoFiH+vcmNzOWvmWWW4fKnMtF0zOJSc/LXm82S8D5Aj31aM8xdP qjaUJ6qmKMwzXgsPiice4/pofz/+/xnfalQ2GLNkoPmSKdQCE4ptbxiJlE2Wa3Med/mnNtlc51k iNApm+S294Tdtd9PYH+/3fNuKMl1d5LnlzXCMZ9HIlQbvSBXhUju20PLFL7QmftMRAsV395fyx X-Received: by 2002:a05:600c:4a22:b0:493:c3e0:c4 with SMTP id 5b1f17b1804b1-493d11f1593mr15161105e9.22.1783151230227; Sat, 04 Jul 2026 00:47:10 -0700 (PDT) Received: from bdtpg (ec2-15-237-197-144.eu-west-3.compute.amazonaws.com. [15.237.197.144]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-47aa039af67sm6880945f8f.17.2026.07.04.00.47.09 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 04 Jul 2026 00:47:09 -0700 (PDT) Date: Sat, 4 Jul 2026 07:47:08 +0000 From: Bertrand Drouvot To: pgsql-hackers@lists.postgresql.org Subject: Fix races conditions in DropRole() and GrantRole() Message-ID: MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="xlWYagR37YwJXkF8" Content-Disposition: inline List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk --xlWYagR37YwJXkF8 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Hi hackers, While working on [1], I observed that DropRole() and GrantRole() have the same "use stale data after the lock is acquired" issues. Indeed, DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. Examples: 1/ DROP ROLE + concurrent DROP ROLE CREATE ROLE testrole; gdb breakpoint at user.c:1198 (before LockSharedObject) on session 1 session 1: DROP ROLE testrole; session 1 is paused by the breakpoint session 2: DROP ROLE testrole; continue session 1 produces: ERROR: could not find tuple for role 24662 2/ GRANT ROLE + concurrent DROP ROLE CREATE ROLE testrole; CREATE ROLE testmember; gdb breakpoint at user.c:1716 (before LockSharedObject) on session 1 session 1: GRANT testrole TO testmember; session is paused by the breakpoint session 2: DROP ROLE testrole; continue session 1: GRANT ROLE succeeds It produces an orphaned pg_auth_members entry: postgres=# SELECT m.member::regrole, m.roleid, r.rolname FROM pg_auth_members m LEFT JOIN pg_roles r ON m.roleid = r.oid WHERE r.oid IS NULL; member | roleid | rolname ------------+--------+--------- testmember | 16386 | The patch attached fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. Remark: AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. [1]: https://postgr.es/m/akZUpiDa1UfmzYxL%40bdtpg Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com --xlWYagR37YwJXkF8 Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="v1-0001-Add-RoleNameGetOid-with-invalidation-based-retry-.patch" From 7b7b46ea877dfb7be33b842bf13711adfbbd1b55 Mon Sep 17 00:00:00 2001 From: Bertrand Drouvot Date: Sat, 4 Jul 2026 04:47:22 +0000 Subject: [PATCH v1] Add RoleNameGetOid() with invalidation-based retry loop for DropRole()/GrantRole() DropRole() and GrantRole() resolve the role name to an OID before acquiring LockSharedObject() on the role. A concurrent session that commits a DROP ROLE between the read and the lock acquisition leaves the first session acting on a stale OID. This commit fixes the races by using the same approach as RangeVarGetRelidExtended(): It encapsulates name resolution, permission checking (via a caller-supplied callback), and lock acquisition inside a retry loop driven by SharedInvalidMessageCounter. If invalidation messages arrive between name resolution and locking, indicating concurrent DDL, the function retries. The lock is kept across retries and only released if the name resolves to a different OID on the next iteration. Two callbacks are provided: - RoleNameCallbackForDropRole(): checks current/session user, superuser attribute, and ADMIN OPTION privilege before locking. This is similar to what DropRole() is currently doing before LockSharedObject(). - RoleNameCallbackForGrantRole(): calls check_role_membership_authorization() to verify the current user can grant/revoke membership. This is similar to what GrantRole() is currently doing before calling AddRoleMems()/DelRoleMems(). DropRole() and GrantRole() now call RoleNameGetOid() with appropriate lock levels. AlterRole() does not need the fix because it calls CatalogTupleUpdate() on the pg_authid tuple before AddRoleMems(), which blocks a concurrent DROP ROLE. Author: Bertrand Drouvot 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--