1 /*-------------------------------------------------------------------------
4 * The superuser() function. Determines if user has superuser privilege.
6 * All code should use either of these two functions to find out
7 * whether a given user is a superuser, rather than examining
8 * pg_authid.rolsuper directly, so that the escape hatch built in for
9 * the single-user case works.
12 * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
17 * src/backend/utils/misc/superuser.c
19 *-------------------------------------------------------------------------
23 #include "access/htup_details.h"
24 #include "catalog/pg_authid.h"
25 #include "miscadmin.h"
26 #include "utils/inval.h"
27 #include "utils/syscache.h"
30 * In common cases the same roleid (ie, the session or current ID) will
31 * be queried repeatedly. So we maintain a simple one-entry cache for
32 * the status of the last requested roleid. The cache can be flushed
33 * at need by watching for cache update events on pg_authid.
35 static Oid last_roleid
= InvalidOid
; /* InvalidOid == cache not valid */
36 static bool last_roleid_is_super
= false;
37 static bool roleid_callback_registered
= false;
39 static void RoleidCallback(Datum arg
, int cacheid
, uint32 hashvalue
);
43 * The Postgres user running this command has Postgres superuser privileges
48 return superuser_arg(GetUserId());
53 * The specified role has Postgres superuser privileges
56 superuser_arg(Oid roleid
)
61 /* Quick out for cache hit */
62 if (OidIsValid(last_roleid
) && last_roleid
== roleid
)
63 return last_roleid_is_super
;
65 /* Special escape path in case you deleted all your users. */
66 if (!IsUnderPostmaster
&& roleid
== BOOTSTRAP_SUPERUSERID
)
69 /* OK, look up the information in pg_authid */
70 rtup
= SearchSysCache1(AUTHOID
, ObjectIdGetDatum(roleid
));
71 if (HeapTupleIsValid(rtup
))
73 result
= ((Form_pg_authid
) GETSTRUCT(rtup
))->rolsuper
;
74 ReleaseSysCache(rtup
);
78 /* Report "not superuser" for invalid roleids */
82 /* If first time through, set up callback for cache flushes */
83 if (!roleid_callback_registered
)
85 CacheRegisterSyscacheCallback(AUTHOID
,
88 roleid_callback_registered
= true;
91 /* Cache the result for next time */
93 last_roleid_is_super
= result
;
100 * Syscache inval callback function
103 RoleidCallback(Datum arg
, int cacheid
, uint32 hashvalue
)
105 /* Invalidate our local cache in case role's superuserness changed */
106 last_roleid
= InvalidOid
;