1 /*-------------------------------------------------------------------------
4 * Basic access control list data structures manipulation routines.
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/utils/adt/acl.c,v 1.142 2008/09/09 18:58:08 tgl Exp $
13 *-------------------------------------------------------------------------
19 #include "catalog/namespace.h"
20 #include "catalog/pg_authid.h"
21 #include "catalog/pg_auth_members.h"
22 #include "catalog/pg_type.h"
23 #include "commands/dbcommands.h"
24 #include "commands/tablespace.h"
25 #include "miscadmin.h"
26 #include "utils/acl.h"
27 #include "utils/builtins.h"
28 #include "utils/inval.h"
29 #include "utils/lsyscache.h"
30 #include "utils/memutils.h"
31 #include "utils/syscache.h"
35 * We frequently need to test whether a given role is a member of some other
36 * role. In most of these tests the "given role" is the same, namely the
37 * active current user. So we can optimize it by keeping a cached list of
38 * all the roles the "given role" is a member of, directly or indirectly.
39 * The cache is flushed whenever we detect a change in pg_auth_members.
41 * There are actually two caches, one computed under "has_privs" rules
42 * (do not recurse where rolinherit isn't true) and one computed under
43 * "is_member" rules (recurse regardless of rolinherit).
45 * Possibly this mechanism should be generalized to allow caching membership
46 * info for multiple roles?
48 * The has_privs cache is:
49 * cached_privs_role is the role OID the cache is for.
50 * cached_privs_roles is an OID list of roles that cached_privs_role
51 * has the privileges of (always including itself).
52 * The cache is valid if cached_privs_role is not InvalidOid.
54 * The is_member cache is similarly:
55 * cached_member_role is the role OID the cache is for.
56 * cached_membership_roles is an OID list of roles that cached_member_role
57 * is a member of (always including itself).
58 * The cache is valid if cached_member_role is not InvalidOid.
60 static Oid cached_privs_role = InvalidOid;
61 static List *cached_privs_roles = NIL;
62 static Oid cached_member_role = InvalidOid;
63 static List *cached_membership_roles = NIL;
66 static const char *getid(const char *s, char *n);
67 static void putid(char *p, const char *s);
68 static Acl *allocacl(int n);
69 static void check_acl(const Acl *acl);
70 static const char *aclparse(const char *s, AclItem *aip);
71 static bool aclitem_match(const AclItem *a1, const AclItem *a2);
72 static void check_circularity(const Acl *old_acl, const AclItem *mod_aip,
74 static Acl *recursive_revoke(Acl *acl, Oid grantee, AclMode revoke_privs,
75 Oid ownerId, DropBehavior behavior);
76 static int oidComparator(const void *arg1, const void *arg2);
78 static AclMode convert_priv_string(text *priv_type_text);
80 static Oid convert_table_name(text *tablename);
81 static AclMode convert_table_priv_string(text *priv_type_text);
82 static Oid convert_database_name(text *databasename);
83 static AclMode convert_database_priv_string(text *priv_type_text);
84 static Oid convert_function_name(text *functionname);
85 static AclMode convert_function_priv_string(text *priv_type_text);
86 static Oid convert_language_name(text *languagename);
87 static AclMode convert_language_priv_string(text *priv_type_text);
88 static Oid convert_schema_name(text *schemaname);
89 static AclMode convert_schema_priv_string(text *priv_type_text);
90 static Oid convert_tablespace_name(text *tablespacename);
91 static AclMode convert_tablespace_priv_string(text *priv_type_text);
92 static AclMode convert_role_priv_string(text *priv_type_text);
93 static AclResult pg_role_aclcheck(Oid role_oid, Oid roleid, AclMode mode);
95 static void RoleMembershipCacheCallback(Datum arg, int cacheid, ItemPointer tuplePtr);
100 * Consumes the first alphanumeric string (identifier) found in string
101 * 's', ignoring any leading white space. If it finds a double quote
102 * it returns the word inside the quotes.
105 * the string position in 's' that points to the next non-space character
106 * in 's', after any quotes. Also:
107 * - loads the identifier into 'n'. (If no identifier is found, 'n'
108 * contains an empty string.) 'n' must be NAMEDATALEN bytes.
111 getid(const char *s, char *n)
114 bool in_quotes = false;
118 while (isspace((unsigned char) *s))
120 /* This code had better match what putid() does, below */
123 (isalnum((unsigned char) *s) ||
131 /* safe to look at next char (could be '\0' though) */
134 in_quotes = !in_quotes;
137 /* it's an escaped double quote; skip the escaping char */
141 /* Add the character to the string */
142 if (len >= NAMEDATALEN - 1)
144 (errcode(ERRCODE_NAME_TOO_LONG),
145 errmsg("identifier too long"),
146 errdetail("Identifier must be less than %d characters.",
152 while (isspace((unsigned char) *s))
158 * Write a role name at *p, adding double quotes if needed.
159 * There must be at least (2*NAMEDATALEN)+2 bytes available at *p.
160 * This needs to be kept in sync with copyAclUserName in pg_dump/dumputils.c
163 putid(char *p, const char *s)
168 for (src = s; *src; src++)
170 /* This test had better match what getid() does, above */
171 if (!isalnum((unsigned char) *src) && *src != '_')
179 for (src = s; *src; src++)
181 /* A double quote character in a username is encoded as "" */
193 * Consumes and parses an ACL specification of the form:
194 * [group|user] [A-Za-z0-9]*=[rwaR]*
195 * from string 's', ignoring any leading white space or white space
196 * between the optional id type keyword (group|user) and the actual
199 * The group|user decoration is unnecessary in the roles world,
200 * but we still accept it for backward compatibility.
202 * This routine is called by the parser as well as aclitemin(), hence
203 * the added generality.
206 * the string position in 's' immediately following the ACL
207 * specification. Also:
208 * - loads the structure pointed to by 'aip' with the appropriate
209 * UID/GID, id type identifier and mode type values.
212 aclparse(const char *s, AclItem *aip)
217 char name[NAMEDATALEN];
218 char name2[NAMEDATALEN];
223 elog(LOG, "aclparse: input = \"%s\"", s);
228 /* we just read a keyword, not a name */
229 if (strcmp(name, "group") != 0 && strcmp(name, "user") != 0)
231 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
232 errmsg("unrecognized key word: \"%s\"", name),
233 errhint("ACL key word must be \"group\" or \"user\".")));
234 s = getid(s, name); /* move s to the name beyond the keyword */
237 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
238 errmsg("missing name"),
239 errhint("A name must follow the \"group\" or \"user\" key word.")));
244 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
245 errmsg("missing \"=\" sign")));
247 privs = goption = ACL_NO_RIGHTS;
249 for (++s, read = 0; isalpha((unsigned char) *s) || *s == '*'; s++)
268 case ACL_TRUNCATE_CHR:
271 case ACL_REFERENCES_CHR:
272 read = ACL_REFERENCES;
274 case ACL_TRIGGER_CHR:
277 case ACL_EXECUTE_CHR:
286 case ACL_CREATE_TEMP_CHR:
287 read = ACL_CREATE_TEMP;
289 case ACL_CONNECT_CHR:
292 case 'R': /* ignore old RULE privileges */
297 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
298 errmsg("invalid mode character: must be one of \"%s\"",
299 ACL_ALL_RIGHTS_STR)));
306 aip->ai_grantee = ACL_ID_PUBLIC;
308 aip->ai_grantee = get_roleid_checked(name);
311 * XXX Allow a degree of backward compatibility by defaulting the grantor
316 s = getid(s + 1, name2);
317 if (name2[0] == '\0')
319 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
320 errmsg("a name must follow the \"/\" sign")));
321 aip->ai_grantor = get_roleid_checked(name2);
325 aip->ai_grantor = BOOTSTRAP_SUPERUSERID;
327 (errcode(ERRCODE_INVALID_GRANTOR),
328 errmsg("defaulting grantor to user ID %u",
329 BOOTSTRAP_SUPERUSERID)));
332 ACLITEM_SET_PRIVS_GOPTIONS(*aip, privs, goption);
335 elog(LOG, "aclparse: correctly read [%u %x %x]",
336 aip->ai_grantee, privs, goption);
344 * Allocates storage for a new Acl with 'n' entries.
356 elog(ERROR, "invalid size: %d", n);
357 size = ACL_N_SIZE(n);
358 new_acl = (Acl *) palloc0(size);
359 SET_VARSIZE(new_acl, size);
361 new_acl->dataoffset = 0; /* we never put in any nulls */
362 new_acl->elemtype = ACLITEMOID;
363 ARR_LBOUND(new_acl)[0] = 1;
364 ARR_DIMS(new_acl)[0] = n;
369 * Verify that an ACL array is acceptable (one-dimensional and has no nulls)
372 check_acl(const Acl *acl)
374 if (ARR_ELEMTYPE(acl) != ACLITEMOID)
376 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
377 errmsg("ACL array contains wrong data type")));
378 if (ARR_NDIM(acl) != 1)
380 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
381 errmsg("ACL arrays must be one-dimensional")));
382 if (ARR_HASNULL(acl))
384 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
385 errmsg("ACL arrays must not contain null values")));
390 * Allocates storage for, and fills in, a new AclItem given a string
391 * 's' that contains an ACL specification. See aclparse for details.
397 aclitemin(PG_FUNCTION_ARGS)
399 const char *s = PG_GETARG_CSTRING(0);
402 aip = (AclItem *) palloc(sizeof(AclItem));
403 s = aclparse(s, aip);
404 while (isspace((unsigned char) *s))
408 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
409 errmsg("extra garbage at the end of the ACL specification")));
411 PG_RETURN_ACLITEM_P(aip);
416 * Allocates storage for, and fills in, a new null-delimited string
417 * containing a formatted ACL specification. See aclparse for details.
423 aclitemout(PG_FUNCTION_ARGS)
425 AclItem *aip = PG_GETARG_ACLITEM_P(0);
431 out = palloc(strlen("=/") +
433 2 * (2 * NAMEDATALEN + 2) +
439 if (aip->ai_grantee != ACL_ID_PUBLIC)
441 htup = SearchSysCache(AUTHOID,
442 ObjectIdGetDatum(aip->ai_grantee),
444 if (HeapTupleIsValid(htup))
446 putid(p, NameStr(((Form_pg_authid) GETSTRUCT(htup))->rolname));
447 ReleaseSysCache(htup);
451 /* Generate numeric OID if we don't find an entry */
452 sprintf(p, "%u", aip->ai_grantee);
460 for (i = 0; i < N_ACL_RIGHTS; ++i)
462 if (ACLITEM_GET_PRIVS(*aip) & (1 << i))
463 *p++ = ACL_ALL_RIGHTS_STR[i];
464 if (ACLITEM_GET_GOPTIONS(*aip) & (1 << i))
471 htup = SearchSysCache(AUTHOID,
472 ObjectIdGetDatum(aip->ai_grantor),
474 if (HeapTupleIsValid(htup))
476 putid(p, NameStr(((Form_pg_authid) GETSTRUCT(htup))->rolname));
477 ReleaseSysCache(htup);
481 /* Generate numeric OID if we don't find an entry */
482 sprintf(p, "%u", aip->ai_grantor);
485 PG_RETURN_CSTRING(out);
490 * Two AclItems are considered to match iff they have the same
491 * grantee and grantor; the privileges are ignored.
494 aclitem_match(const AclItem *a1, const AclItem *a2)
496 return a1->ai_grantee == a2->ai_grantee &&
497 a1->ai_grantor == a2->ai_grantor;
501 * aclitem equality operator
504 aclitem_eq(PG_FUNCTION_ARGS)
506 AclItem *a1 = PG_GETARG_ACLITEM_P(0);
507 AclItem *a2 = PG_GETARG_ACLITEM_P(1);
510 result = a1->ai_privs == a2->ai_privs &&
511 a1->ai_grantee == a2->ai_grantee &&
512 a1->ai_grantor == a2->ai_grantor;
513 PG_RETURN_BOOL(result);
517 * aclitem hash function
519 * We make aclitems hashable not so much because anyone is likely to hash
520 * them, as because we want array equality to work on aclitem arrays, and
521 * with the typcache mechanism we must have a hash or btree opclass.
524 hash_aclitem(PG_FUNCTION_ARGS)
526 AclItem *a = PG_GETARG_ACLITEM_P(0);
528 /* not very bright, but avoids any issue of padding in struct */
529 PG_RETURN_UINT32((uint32) (a->ai_privs + a->ai_grantee + a->ai_grantor));
534 * acldefault() --- create an ACL describing default access permissions
536 * Change this routine if you want to alter the default access policy for
537 * newly-created objects (or any object with a NULL acl entry).
540 acldefault(GrantObjectType objtype, Oid ownerId)
542 AclMode world_default;
543 AclMode owner_default;
549 case ACL_OBJECT_RELATION:
550 world_default = ACL_NO_RIGHTS;
551 owner_default = ACL_ALL_RIGHTS_RELATION;
553 case ACL_OBJECT_SEQUENCE:
554 world_default = ACL_NO_RIGHTS;
555 owner_default = ACL_ALL_RIGHTS_SEQUENCE;
557 case ACL_OBJECT_DATABASE:
558 /* for backwards compatibility, grant some rights by default */
559 world_default = ACL_CREATE_TEMP | ACL_CONNECT;
560 owner_default = ACL_ALL_RIGHTS_DATABASE;
562 case ACL_OBJECT_FUNCTION:
563 /* Grant EXECUTE by default, for now */
564 world_default = ACL_EXECUTE;
565 owner_default = ACL_ALL_RIGHTS_FUNCTION;
567 case ACL_OBJECT_LANGUAGE:
568 /* Grant USAGE by default, for now */
569 world_default = ACL_USAGE;
570 owner_default = ACL_ALL_RIGHTS_LANGUAGE;
572 case ACL_OBJECT_NAMESPACE:
573 world_default = ACL_NO_RIGHTS;
574 owner_default = ACL_ALL_RIGHTS_NAMESPACE;
576 case ACL_OBJECT_TABLESPACE:
577 world_default = ACL_NO_RIGHTS;
578 owner_default = ACL_ALL_RIGHTS_TABLESPACE;
581 elog(ERROR, "unrecognized objtype: %d", (int) objtype);
582 world_default = ACL_NO_RIGHTS; /* keep compiler quiet */
583 owner_default = ACL_NO_RIGHTS;
587 acl = allocacl((world_default != ACL_NO_RIGHTS) ? 2 : 1);
590 if (world_default != ACL_NO_RIGHTS)
592 aip->ai_grantee = ACL_ID_PUBLIC;
593 aip->ai_grantor = ownerId;
594 ACLITEM_SET_PRIVS_GOPTIONS(*aip, world_default, ACL_NO_RIGHTS);
599 * Note that the owner's entry shows all ordinary privileges but no grant
600 * options. This is because his grant options come "from the system" and
601 * not from his own efforts. (The SQL spec says that the owner's rights
602 * come from a "_SYSTEM" authid.) However, we do consider that the
603 * owner's ordinary privileges are self-granted; this lets him revoke
604 * them. We implement the owner's grant options without any explicit
605 * "_SYSTEM"-like ACL entry, by internally special-casing the owner
606 * whereever we are testing grant options.
608 aip->ai_grantee = ownerId;
609 aip->ai_grantor = ownerId;
610 ACLITEM_SET_PRIVS_GOPTIONS(*aip, owner_default, ACL_NO_RIGHTS);
617 * Update an ACL array to add or remove specified privileges.
619 * old_acl: the input ACL array
620 * mod_aip: defines the privileges to be added, removed, or substituted
621 * modechg: ACL_MODECHG_ADD, ACL_MODECHG_DEL, or ACL_MODECHG_EQL
622 * ownerId: Oid of object owner
623 * behavior: RESTRICT or CASCADE behavior for recursive removal
625 * ownerid and behavior are only relevant when the update operation specifies
626 * deletion of grant options.
628 * The result is a modified copy; the input object is not changed.
630 * NB: caller is responsible for having detoasted the input ACL, if needed.
633 aclupdate(const Acl *old_acl, const AclItem *mod_aip,
634 int modechg, Oid ownerId, DropBehavior behavior)
646 /* Caller probably already checked old_acl, but be safe */
649 /* If granting grant options, check for circularity */
650 if (modechg != ACL_MODECHG_DEL &&
651 ACLITEM_GET_GOPTIONS(*mod_aip) != ACL_NO_RIGHTS)
652 check_circularity(old_acl, mod_aip, ownerId);
654 num = ACL_NUM(old_acl);
655 old_aip = ACL_DAT(old_acl);
658 * Search the ACL for an existing entry for this grantee and grantor. If
659 * one exists, just modify the entry in-place (well, in the same position,
660 * since we actually return a copy); otherwise, insert the new entry at
664 for (dst = 0; dst < num; ++dst)
666 if (aclitem_match(mod_aip, old_aip + dst))
668 /* found a match, so modify existing item */
669 new_acl = allocacl(num);
670 new_aip = ACL_DAT(new_acl);
671 memcpy(new_acl, old_acl, ACL_SIZE(old_acl));
678 /* need to append a new item */
679 new_acl = allocacl(num + 1);
680 new_aip = ACL_DAT(new_acl);
681 memcpy(new_aip, old_aip, num * sizeof(AclItem));
683 /* initialize the new entry with no permissions */
684 new_aip[dst].ai_grantee = mod_aip->ai_grantee;
685 new_aip[dst].ai_grantor = mod_aip->ai_grantor;
686 ACLITEM_SET_PRIVS_GOPTIONS(new_aip[dst],
687 ACL_NO_RIGHTS, ACL_NO_RIGHTS);
688 num++; /* set num to the size of new_acl */
691 old_rights = ACLITEM_GET_RIGHTS(new_aip[dst]);
692 old_goptions = ACLITEM_GET_GOPTIONS(new_aip[dst]);
694 /* apply the specified permissions change */
697 case ACL_MODECHG_ADD:
698 ACLITEM_SET_RIGHTS(new_aip[dst],
699 old_rights | ACLITEM_GET_RIGHTS(*mod_aip));
701 case ACL_MODECHG_DEL:
702 ACLITEM_SET_RIGHTS(new_aip[dst],
703 old_rights & ~ACLITEM_GET_RIGHTS(*mod_aip));
705 case ACL_MODECHG_EQL:
706 ACLITEM_SET_RIGHTS(new_aip[dst],
707 ACLITEM_GET_RIGHTS(*mod_aip));
711 new_rights = ACLITEM_GET_RIGHTS(new_aip[dst]);
712 new_goptions = ACLITEM_GET_GOPTIONS(new_aip[dst]);
715 * If the adjusted entry has no permissions, delete it from the list.
717 if (new_rights == ACL_NO_RIGHTS)
719 memmove(new_aip + dst,
721 (num - dst - 1) * sizeof(AclItem));
722 /* Adjust array size to be 'num - 1' items */
723 ARR_DIMS(new_acl)[0] = num - 1;
724 SET_VARSIZE(new_acl, ACL_N_SIZE(num - 1));
728 * Remove abandoned privileges (cascading revoke). Currently we can only
729 * handle this when the grantee is not PUBLIC.
731 if ((old_goptions & ~new_goptions) != 0)
733 Assert(mod_aip->ai_grantee != ACL_ID_PUBLIC);
734 new_acl = recursive_revoke(new_acl, mod_aip->ai_grantee,
735 (old_goptions & ~new_goptions),
743 * Update an ACL array to reflect a change of owner to the parent object
745 * old_acl: the input ACL array (must not be NULL)
746 * oldOwnerId: Oid of the old object owner
747 * newOwnerId: Oid of the new object owner
749 * The result is a modified copy; the input object is not changed.
751 * NB: caller is responsible for having detoasted the input ACL, if needed.
754 aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
762 bool newpresent = false;
771 * Make a copy of the given ACL, substituting new owner ID for old
772 * wherever it appears as either grantor or grantee. Also note if the new
773 * owner ID is already present.
775 num = ACL_NUM(old_acl);
776 old_aip = ACL_DAT(old_acl);
777 new_acl = allocacl(num);
778 new_aip = ACL_DAT(new_acl);
779 memcpy(new_aip, old_aip, num * sizeof(AclItem));
780 for (dst = 0, dst_aip = new_aip; dst < num; dst++, dst_aip++)
782 if (dst_aip->ai_grantor == oldOwnerId)
783 dst_aip->ai_grantor = newOwnerId;
784 else if (dst_aip->ai_grantor == newOwnerId)
786 if (dst_aip->ai_grantee == oldOwnerId)
787 dst_aip->ai_grantee = newOwnerId;
788 else if (dst_aip->ai_grantee == newOwnerId)
793 * If the old ACL contained any references to the new owner, then we may
794 * now have generated an ACL containing duplicate entries. Find them and
795 * merge them so that there are not duplicates. (This is relatively
796 * expensive since we use a stupid O(N^2) algorithm, but it's unlikely to
797 * be the normal case.)
799 * To simplify deletion of duplicate entries, we temporarily leave them in
800 * the array but set their privilege masks to zero; when we reach such an
801 * entry it's just skipped. (Thus, a side effect of this code will be to
802 * remove privilege-free entries, should there be any in the input.) dst
803 * is the next output slot, targ is the currently considered input slot
804 * (always >= dst), and src scans entries to the right of targ looking for
805 * duplicates. Once an entry has been emitted to dst it is known
806 * duplicate-free and need not be considered anymore.
811 for (targ = 0, targ_aip = new_aip; targ < num; targ++, targ_aip++)
813 /* ignore if deleted in an earlier pass */
814 if (ACLITEM_GET_RIGHTS(*targ_aip) == ACL_NO_RIGHTS)
816 /* find and merge any duplicates */
817 for (src = targ + 1, src_aip = targ_aip + 1; src < num;
820 if (ACLITEM_GET_RIGHTS(*src_aip) == ACL_NO_RIGHTS)
822 if (aclitem_match(targ_aip, src_aip))
824 ACLITEM_SET_RIGHTS(*targ_aip,
825 ACLITEM_GET_RIGHTS(*targ_aip) |
826 ACLITEM_GET_RIGHTS(*src_aip));
827 /* mark the duplicate deleted */
828 ACLITEM_SET_RIGHTS(*src_aip, ACL_NO_RIGHTS);
831 /* and emit to output */
832 new_aip[dst] = *targ_aip;
835 /* Adjust array size to be 'dst' items */
836 ARR_DIMS(new_acl)[0] = dst;
837 SET_VARSIZE(new_acl, ACL_N_SIZE(dst));
845 * When granting grant options, we must disallow attempts to set up circular
846 * chains of grant options. Suppose A (the object owner) grants B some
847 * privileges with grant option, and B re-grants them to C. If C could
848 * grant the privileges to B as well, then A would be unable to effectively
849 * revoke the privileges from B, since recursive_revoke would consider that
850 * B still has 'em from C.
852 * We check for this by recursively deleting all grant options belonging to
853 * the target grantee, and then seeing if the would-be grantor still has the
854 * grant option or not.
857 check_circularity(const Acl *old_acl, const AclItem *mod_aip,
869 * For now, grant options can only be granted to roles, not PUBLIC.
870 * Otherwise we'd have to work a bit harder here.
872 Assert(mod_aip->ai_grantee != ACL_ID_PUBLIC);
874 /* The owner always has grant options, no need to check */
875 if (mod_aip->ai_grantor == ownerId)
878 /* Make a working copy */
879 acl = allocacl(ACL_NUM(old_acl));
880 memcpy(acl, old_acl, ACL_SIZE(old_acl));
882 /* Zap all grant options of target grantee, plus what depends on 'em */
886 for (i = 0; i < num; i++)
888 if (aip[i].ai_grantee == mod_aip->ai_grantee &&
889 ACLITEM_GET_GOPTIONS(aip[i]) != ACL_NO_RIGHTS)
893 /* We'll actually zap ordinary privs too, but no matter */
894 new_acl = aclupdate(acl, &aip[i], ACL_MODECHG_DEL,
895 ownerId, DROP_CASCADE);
904 /* Now we can compute grantor's independently-derived privileges */
905 own_privs = aclmask(acl,
908 ACL_GRANT_OPTION_FOR(ACLITEM_GET_GOPTIONS(*mod_aip)),
910 own_privs = ACL_OPTION_TO_PRIVS(own_privs);
912 if ((ACLITEM_GET_GOPTIONS(*mod_aip) & ~own_privs) != 0)
914 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
915 errmsg("grant options cannot be granted back to your own grantor")));
922 * Ensure that no privilege is "abandoned". A privilege is abandoned
923 * if the user that granted the privilege loses the grant option. (So
924 * the chain through which it was granted is broken.) Either the
925 * abandoned privileges are revoked as well, or an error message is
926 * printed, depending on the drop behavior option.
928 * acl: the input ACL list
929 * grantee: the user from whom some grant options have been revoked
930 * revoke_privs: the grant options being revoked
931 * ownerId: Oid of object owner
932 * behavior: RESTRICT or CASCADE behavior for recursive removal
934 * The input Acl object is pfree'd if replaced.
937 recursive_revoke(Acl *acl,
939 AclMode revoke_privs,
941 DropBehavior behavior)
950 /* The owner can never truly lose grant options, so short-circuit */
951 if (grantee == ownerId)
954 /* The grantee might still have the privileges via another grantor */
955 still_has = aclmask(acl, grantee, ownerId,
956 ACL_GRANT_OPTION_FOR(revoke_privs),
958 revoke_privs &= ~still_has;
959 if (revoke_privs == ACL_NO_RIGHTS)
965 for (i = 0; i < num; i++)
967 if (aip[i].ai_grantor == grantee
968 && (ACLITEM_GET_PRIVS(aip[i]) & revoke_privs) != 0)
973 if (behavior == DROP_RESTRICT)
975 (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
976 errmsg("dependent privileges exist"),
977 errhint("Use CASCADE to revoke them too.")));
979 mod_acl.ai_grantor = grantee;
980 mod_acl.ai_grantee = aip[i].ai_grantee;
981 ACLITEM_SET_PRIVS_GOPTIONS(mod_acl,
985 new_acl = aclupdate(acl, &mod_acl, ACL_MODECHG_DEL,
1000 * aclmask --- compute bitmask of all privileges held by roleid.
1002 * When 'how' = ACLMASK_ALL, this simply returns the privilege bits
1003 * held by the given roleid according to the given ACL list, ANDed
1004 * with 'mask'. (The point of passing 'mask' is to let the routine
1005 * exit early if all privileges of interest have been found.)
1007 * When 'how' = ACLMASK_ANY, returns as soon as any bit in the mask
1008 * is known true. (This lets us exit soonest in cases where the
1009 * caller is only going to test for zero or nonzero result.)
1013 * To see if any of a set of privileges are held:
1014 * if (aclmask(acl, roleid, ownerId, privs, ACLMASK_ANY) != 0)
1016 * To see if all of a set of privileges are held:
1017 * if (aclmask(acl, roleid, ownerId, privs, ACLMASK_ALL) == privs)
1019 * To determine exactly which of a set of privileges are held:
1020 * heldprivs = aclmask(acl, roleid, ownerId, privs, ACLMASK_ALL);
1023 aclmask(const Acl *acl, Oid roleid, Oid ownerId,
1024 AclMode mask, AclMaskHow how)
1033 * Null ACL should not happen, since caller should have inserted
1034 * appropriate default
1037 elog(ERROR, "null ACL");
1041 /* Quick exit for mask == 0 */
1047 /* Owner always implicitly has all grant options */
1048 if ((mask & ACLITEM_ALL_GOPTION_BITS) &&
1049 has_privs_of_role(roleid, ownerId))
1051 result = mask & ACLITEM_ALL_GOPTION_BITS;
1052 if ((how == ACLMASK_ALL) ? (result == mask) : (result != 0))
1057 aidat = ACL_DAT(acl);
1060 * Check privileges granted directly to roleid or to public
1062 for (i = 0; i < num; i++)
1064 AclItem *aidata = &aidat[i];
1066 if (aidata->ai_grantee == ACL_ID_PUBLIC ||
1067 aidata->ai_grantee == roleid)
1069 result |= aidata->ai_privs & mask;
1070 if ((how == ACLMASK_ALL) ? (result == mask) : (result != 0))
1076 * Check privileges granted indirectly via role memberships. We do this in
1077 * a separate pass to minimize expensive indirect membership tests. In
1078 * particular, it's worth testing whether a given ACL entry grants any
1079 * privileges still of interest before we perform the has_privs_of_role
1082 remaining = mask & ~result;
1083 for (i = 0; i < num; i++)
1085 AclItem *aidata = &aidat[i];
1087 if (aidata->ai_grantee == ACL_ID_PUBLIC ||
1088 aidata->ai_grantee == roleid)
1089 continue; /* already checked it */
1091 if ((aidata->ai_privs & remaining) &&
1092 has_privs_of_role(roleid, aidata->ai_grantee))
1094 result |= aidata->ai_privs & mask;
1095 if ((how == ACLMASK_ALL) ? (result == mask) : (result != 0))
1097 remaining = mask & ~result;
1106 * aclmask_direct --- compute bitmask of all privileges held by roleid.
1108 * This is exactly like aclmask() except that we consider only privileges
1109 * held *directly* by roleid, not those inherited via role membership.
1112 aclmask_direct(const Acl *acl, Oid roleid, Oid ownerId,
1113 AclMode mask, AclMaskHow how)
1121 * Null ACL should not happen, since caller should have inserted
1122 * appropriate default
1125 elog(ERROR, "null ACL");
1129 /* Quick exit for mask == 0 */
1135 /* Owner always implicitly has all grant options */
1136 if ((mask & ACLITEM_ALL_GOPTION_BITS) &&
1139 result = mask & ACLITEM_ALL_GOPTION_BITS;
1140 if ((how == ACLMASK_ALL) ? (result == mask) : (result != 0))
1145 aidat = ACL_DAT(acl);
1148 * Check privileges granted directly to roleid (and not to public)
1150 for (i = 0; i < num; i++)
1152 AclItem *aidata = &aidat[i];
1154 if (aidata->ai_grantee == roleid)
1156 result |= aidata->ai_privs & mask;
1157 if ((how == ACLMASK_ALL) ? (result == mask) : (result != 0))
1168 * Find out all the roleids mentioned in an Acl.
1169 * Note that we do not distinguish grantors from grantees.
1171 * *roleids is set to point to a palloc'd array containing distinct OIDs
1172 * in sorted order. The length of the array is the function result.
1175 aclmembers(const Acl *acl, Oid **roleids)
1178 const AclItem *acldat;
1183 if (acl == NULL || ACL_NUM(acl) == 0)
1191 /* Allocate the worst-case space requirement */
1192 list = palloc(ACL_NUM(acl) * 2 * sizeof(Oid));
1193 acldat = ACL_DAT(acl);
1196 * Walk the ACL collecting mentioned RoleIds.
1199 for (i = 0; i < ACL_NUM(acl); i++)
1201 const AclItem *ai = &acldat[i];
1203 if (ai->ai_grantee != ACL_ID_PUBLIC)
1204 list[j++] = ai->ai_grantee;
1205 /* grantor is currently never PUBLIC, but let's check anyway */
1206 if (ai->ai_grantor != ACL_ID_PUBLIC)
1207 list[j++] = ai->ai_grantor;
1210 /* Sort the array */
1211 qsort(list, j, sizeof(Oid), oidComparator);
1213 /* Remove duplicates from the array */
1215 for (i = 1; i < j; i++)
1217 if (list[k] != list[i])
1218 list[++k] = list[i];
1222 * We could repalloc the array down to minimum size, but it's hardly worth
1223 * it since it's only transient memory.
1232 * qsort comparison function for Oids
1235 oidComparator(const void *arg1, const void *arg2)
1237 Oid oid1 = *(const Oid *) arg1;
1238 Oid oid2 = *(const Oid *) arg2;
1249 * aclinsert (exported function)
1252 aclinsert(PG_FUNCTION_ARGS)
1255 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1256 errmsg("aclinsert is no longer supported")));
1258 PG_RETURN_NULL(); /* keep compiler quiet */
1262 aclremove(PG_FUNCTION_ARGS)
1265 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1266 errmsg("aclremove is no longer supported")));
1268 PG_RETURN_NULL(); /* keep compiler quiet */
1272 aclcontains(PG_FUNCTION_ARGS)
1274 Acl *acl = PG_GETARG_ACL_P(0);
1275 AclItem *aip = PG_GETARG_ACLITEM_P(1);
1282 aidat = ACL_DAT(acl);
1283 for (i = 0; i < num; ++i)
1285 if (aip->ai_grantee == aidat[i].ai_grantee &&
1286 aip->ai_grantor == aidat[i].ai_grantor &&
1287 (ACLITEM_GET_RIGHTS(*aip) & ACLITEM_GET_RIGHTS(aidat[i])) == ACLITEM_GET_RIGHTS(*aip))
1288 PG_RETURN_BOOL(true);
1290 PG_RETURN_BOOL(false);
1294 makeaclitem(PG_FUNCTION_ARGS)
1296 Oid grantee = PG_GETARG_OID(0);
1297 Oid grantor = PG_GETARG_OID(1);
1298 text *privtext = PG_GETARG_TEXT_P(2);
1299 bool goption = PG_GETARG_BOOL(3);
1303 priv = convert_priv_string(privtext);
1305 result = (AclItem *) palloc(sizeof(AclItem));
1307 result->ai_grantee = grantee;
1308 result->ai_grantor = grantor;
1310 ACLITEM_SET_PRIVS_GOPTIONS(*result, priv,
1311 (goption ? priv : ACL_NO_RIGHTS));
1313 PG_RETURN_ACLITEM_P(result);
1317 convert_priv_string(text *priv_type_text)
1319 char *priv_type = text_to_cstring(priv_type_text);
1321 if (pg_strcasecmp(priv_type, "SELECT") == 0)
1323 if (pg_strcasecmp(priv_type, "INSERT") == 0)
1325 if (pg_strcasecmp(priv_type, "UPDATE") == 0)
1327 if (pg_strcasecmp(priv_type, "DELETE") == 0)
1329 if (pg_strcasecmp(priv_type, "TRUNCATE") == 0)
1330 return ACL_TRUNCATE;
1331 if (pg_strcasecmp(priv_type, "REFERENCES") == 0)
1332 return ACL_REFERENCES;
1333 if (pg_strcasecmp(priv_type, "TRIGGER") == 0)
1335 if (pg_strcasecmp(priv_type, "EXECUTE") == 0)
1337 if (pg_strcasecmp(priv_type, "USAGE") == 0)
1339 if (pg_strcasecmp(priv_type, "CREATE") == 0)
1341 if (pg_strcasecmp(priv_type, "TEMP") == 0)
1342 return ACL_CREATE_TEMP;
1343 if (pg_strcasecmp(priv_type, "TEMPORARY") == 0)
1344 return ACL_CREATE_TEMP;
1345 if (pg_strcasecmp(priv_type, "CONNECT") == 0)
1347 if (pg_strcasecmp(priv_type, "RULE") == 0)
1348 return 0; /* ignore old RULE privileges */
1351 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1352 errmsg("unrecognized privilege type: \"%s\"", priv_type)));
1353 return ACL_NO_RIGHTS; /* keep compiler quiet */
1358 * has_table_privilege variants
1359 * These are all named "has_table_privilege" at the SQL level.
1360 * They take various combinations of relation name, relation OID,
1361 * user name, user OID, or implicit user = current_user.
1363 * The result is a boolean value: true if user has the indicated
1364 * privilege, false if not.
1368 * has_table_privilege_name_name
1369 * Check user privileges on a table given
1370 * name username, text tablename, and text priv name.
1373 has_table_privilege_name_name(PG_FUNCTION_ARGS)
1375 Name rolename = PG_GETARG_NAME(0);
1376 text *tablename = PG_GETARG_TEXT_P(1);
1377 text *priv_type_text = PG_GETARG_TEXT_P(2);
1381 AclResult aclresult;
1383 roleid = get_roleid_checked(NameStr(*rolename));
1384 tableoid = convert_table_name(tablename);
1385 mode = convert_table_priv_string(priv_type_text);
1387 aclresult = pg_class_aclcheck(tableoid, roleid, mode);
1389 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1393 * has_table_privilege_name
1394 * Check user privileges on a table given
1395 * text tablename and text priv name.
1396 * current_user is assumed
1399 has_table_privilege_name(PG_FUNCTION_ARGS)
1401 text *tablename = PG_GETARG_TEXT_P(0);
1402 text *priv_type_text = PG_GETARG_TEXT_P(1);
1406 AclResult aclresult;
1408 roleid = GetUserId();
1409 tableoid = convert_table_name(tablename);
1410 mode = convert_table_priv_string(priv_type_text);
1412 aclresult = pg_class_aclcheck(tableoid, roleid, mode);
1414 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1418 * has_table_privilege_name_id
1419 * Check user privileges on a table given
1420 * name usename, table oid, and text priv name.
1423 has_table_privilege_name_id(PG_FUNCTION_ARGS)
1425 Name username = PG_GETARG_NAME(0);
1426 Oid tableoid = PG_GETARG_OID(1);
1427 text *priv_type_text = PG_GETARG_TEXT_P(2);
1430 AclResult aclresult;
1432 roleid = get_roleid_checked(NameStr(*username));
1433 mode = convert_table_priv_string(priv_type_text);
1435 aclresult = pg_class_aclcheck(tableoid, roleid, mode);
1437 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1441 * has_table_privilege_id
1442 * Check user privileges on a table given
1443 * table oid, and text priv name.
1444 * current_user is assumed
1447 has_table_privilege_id(PG_FUNCTION_ARGS)
1449 Oid tableoid = PG_GETARG_OID(0);
1450 text *priv_type_text = PG_GETARG_TEXT_P(1);
1453 AclResult aclresult;
1455 roleid = GetUserId();
1456 mode = convert_table_priv_string(priv_type_text);
1458 aclresult = pg_class_aclcheck(tableoid, roleid, mode);
1460 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1464 * has_table_privilege_id_name
1465 * Check user privileges on a table given
1466 * roleid, text tablename, and text priv name.
1469 has_table_privilege_id_name(PG_FUNCTION_ARGS)
1471 Oid roleid = PG_GETARG_OID(0);
1472 text *tablename = PG_GETARG_TEXT_P(1);
1473 text *priv_type_text = PG_GETARG_TEXT_P(2);
1476 AclResult aclresult;
1478 tableoid = convert_table_name(tablename);
1479 mode = convert_table_priv_string(priv_type_text);
1481 aclresult = pg_class_aclcheck(tableoid, roleid, mode);
1483 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1487 * has_table_privilege_id_id
1488 * Check user privileges on a table given
1489 * roleid, table oid, and text priv name.
1492 has_table_privilege_id_id(PG_FUNCTION_ARGS)
1494 Oid roleid = PG_GETARG_OID(0);
1495 Oid tableoid = PG_GETARG_OID(1);
1496 text *priv_type_text = PG_GETARG_TEXT_P(2);
1498 AclResult aclresult;
1500 mode = convert_table_priv_string(priv_type_text);
1502 aclresult = pg_class_aclcheck(tableoid, roleid, mode);
1504 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1508 * Support routines for has_table_privilege family.
1512 * Given a table name expressed as a string, look it up and return Oid
1515 convert_table_name(text *tablename)
1519 relrv = makeRangeVarFromNameList(textToQualifiedNameList(tablename));
1521 return RangeVarGetRelid(relrv, false);
1525 * convert_table_priv_string
1526 * Convert text string to AclMode value.
1529 convert_table_priv_string(text *priv_type_text)
1531 char *priv_type = text_to_cstring(priv_type_text);
1534 * Return mode from priv_type string
1536 if (pg_strcasecmp(priv_type, "SELECT") == 0)
1538 if (pg_strcasecmp(priv_type, "SELECT WITH GRANT OPTION") == 0)
1539 return ACL_GRANT_OPTION_FOR(ACL_SELECT);
1541 if (pg_strcasecmp(priv_type, "INSERT") == 0)
1543 if (pg_strcasecmp(priv_type, "INSERT WITH GRANT OPTION") == 0)
1544 return ACL_GRANT_OPTION_FOR(ACL_INSERT);
1546 if (pg_strcasecmp(priv_type, "UPDATE") == 0)
1548 if (pg_strcasecmp(priv_type, "UPDATE WITH GRANT OPTION") == 0)
1549 return ACL_GRANT_OPTION_FOR(ACL_UPDATE);
1551 if (pg_strcasecmp(priv_type, "DELETE") == 0)
1553 if (pg_strcasecmp(priv_type, "DELETE WITH GRANT OPTION") == 0)
1554 return ACL_GRANT_OPTION_FOR(ACL_DELETE);
1556 if (pg_strcasecmp(priv_type, "TRUNCATE") == 0)
1557 return ACL_TRUNCATE;
1558 if (pg_strcasecmp(priv_type, "TRUNCATE WITH GRANT OPTION") == 0)
1559 return ACL_GRANT_OPTION_FOR(ACL_TRUNCATE);
1561 if (pg_strcasecmp(priv_type, "REFERENCES") == 0)
1562 return ACL_REFERENCES;
1563 if (pg_strcasecmp(priv_type, "REFERENCES WITH GRANT OPTION") == 0)
1564 return ACL_GRANT_OPTION_FOR(ACL_REFERENCES);
1566 if (pg_strcasecmp(priv_type, "TRIGGER") == 0)
1568 if (pg_strcasecmp(priv_type, "TRIGGER WITH GRANT OPTION") == 0)
1569 return ACL_GRANT_OPTION_FOR(ACL_TRIGGER);
1571 if (pg_strcasecmp(priv_type, "RULE") == 0)
1572 return 0; /* ignore old RULE privileges */
1573 if (pg_strcasecmp(priv_type, "RULE WITH GRANT OPTION") == 0)
1577 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1578 errmsg("unrecognized privilege type: \"%s\"", priv_type)));
1579 return ACL_NO_RIGHTS; /* keep compiler quiet */
1584 * has_database_privilege variants
1585 * These are all named "has_database_privilege" at the SQL level.
1586 * They take various combinations of database name, database OID,
1587 * user name, user OID, or implicit user = current_user.
1589 * The result is a boolean value: true if user has the indicated
1590 * privilege, false if not.
1594 * has_database_privilege_name_name
1595 * Check user privileges on a database given
1596 * name username, text databasename, and text priv name.
1599 has_database_privilege_name_name(PG_FUNCTION_ARGS)
1601 Name username = PG_GETARG_NAME(0);
1602 text *databasename = PG_GETARG_TEXT_P(1);
1603 text *priv_type_text = PG_GETARG_TEXT_P(2);
1607 AclResult aclresult;
1609 roleid = get_roleid_checked(NameStr(*username));
1610 databaseoid = convert_database_name(databasename);
1611 mode = convert_database_priv_string(priv_type_text);
1613 aclresult = pg_database_aclcheck(databaseoid, roleid, mode);
1615 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1619 * has_database_privilege_name
1620 * Check user privileges on a database given
1621 * text databasename and text priv name.
1622 * current_user is assumed
1625 has_database_privilege_name(PG_FUNCTION_ARGS)
1627 text *databasename = PG_GETARG_TEXT_P(0);
1628 text *priv_type_text = PG_GETARG_TEXT_P(1);
1632 AclResult aclresult;
1634 roleid = GetUserId();
1635 databaseoid = convert_database_name(databasename);
1636 mode = convert_database_priv_string(priv_type_text);
1638 aclresult = pg_database_aclcheck(databaseoid, roleid, mode);
1640 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1644 * has_database_privilege_name_id
1645 * Check user privileges on a database given
1646 * name usename, database oid, and text priv name.
1649 has_database_privilege_name_id(PG_FUNCTION_ARGS)
1651 Name username = PG_GETARG_NAME(0);
1652 Oid databaseoid = PG_GETARG_OID(1);
1653 text *priv_type_text = PG_GETARG_TEXT_P(2);
1656 AclResult aclresult;
1658 roleid = get_roleid_checked(NameStr(*username));
1659 mode = convert_database_priv_string(priv_type_text);
1661 aclresult = pg_database_aclcheck(databaseoid, roleid, mode);
1663 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1667 * has_database_privilege_id
1668 * Check user privileges on a database given
1669 * database oid, and text priv name.
1670 * current_user is assumed
1673 has_database_privilege_id(PG_FUNCTION_ARGS)
1675 Oid databaseoid = PG_GETARG_OID(0);
1676 text *priv_type_text = PG_GETARG_TEXT_P(1);
1679 AclResult aclresult;
1681 roleid = GetUserId();
1682 mode = convert_database_priv_string(priv_type_text);
1684 aclresult = pg_database_aclcheck(databaseoid, roleid, mode);
1686 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1690 * has_database_privilege_id_name
1691 * Check user privileges on a database given
1692 * roleid, text databasename, and text priv name.
1695 has_database_privilege_id_name(PG_FUNCTION_ARGS)
1697 Oid roleid = PG_GETARG_OID(0);
1698 text *databasename = PG_GETARG_TEXT_P(1);
1699 text *priv_type_text = PG_GETARG_TEXT_P(2);
1702 AclResult aclresult;
1704 databaseoid = convert_database_name(databasename);
1705 mode = convert_database_priv_string(priv_type_text);
1707 aclresult = pg_database_aclcheck(databaseoid, roleid, mode);
1709 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1713 * has_database_privilege_id_id
1714 * Check user privileges on a database given
1715 * roleid, database oid, and text priv name.
1718 has_database_privilege_id_id(PG_FUNCTION_ARGS)
1720 Oid roleid = PG_GETARG_OID(0);
1721 Oid databaseoid = PG_GETARG_OID(1);
1722 text *priv_type_text = PG_GETARG_TEXT_P(2);
1724 AclResult aclresult;
1726 mode = convert_database_priv_string(priv_type_text);
1728 aclresult = pg_database_aclcheck(databaseoid, roleid, mode);
1730 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1734 * Support routines for has_database_privilege family.
1738 * Given a database name expressed as a string, look it up and return Oid
1741 convert_database_name(text *databasename)
1743 char *dbname = text_to_cstring(databasename);
1746 oid = get_database_oid(dbname);
1747 if (!OidIsValid(oid))
1749 (errcode(ERRCODE_UNDEFINED_DATABASE),
1750 errmsg("database \"%s\" does not exist", dbname)));
1756 * convert_database_priv_string
1757 * Convert text string to AclMode value.
1760 convert_database_priv_string(text *priv_type_text)
1762 char *priv_type = text_to_cstring(priv_type_text);
1765 * Return mode from priv_type string
1767 if (pg_strcasecmp(priv_type, "CREATE") == 0)
1769 if (pg_strcasecmp(priv_type, "CREATE WITH GRANT OPTION") == 0)
1770 return ACL_GRANT_OPTION_FOR(ACL_CREATE);
1772 if (pg_strcasecmp(priv_type, "TEMPORARY") == 0)
1773 return ACL_CREATE_TEMP;
1774 if (pg_strcasecmp(priv_type, "TEMPORARY WITH GRANT OPTION") == 0)
1775 return ACL_GRANT_OPTION_FOR(ACL_CREATE_TEMP);
1777 if (pg_strcasecmp(priv_type, "TEMP") == 0)
1778 return ACL_CREATE_TEMP;
1779 if (pg_strcasecmp(priv_type, "TEMP WITH GRANT OPTION") == 0)
1780 return ACL_GRANT_OPTION_FOR(ACL_CREATE_TEMP);
1782 if (pg_strcasecmp(priv_type, "CONNECT") == 0)
1784 if (pg_strcasecmp(priv_type, "CONNECT WITH GRANT OPTION") == 0)
1785 return ACL_GRANT_OPTION_FOR(ACL_CONNECT);
1788 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1789 errmsg("unrecognized privilege type: \"%s\"", priv_type)));
1790 return ACL_NO_RIGHTS; /* keep compiler quiet */
1795 * has_function_privilege variants
1796 * These are all named "has_function_privilege" at the SQL level.
1797 * They take various combinations of function name, function OID,
1798 * user name, user OID, or implicit user = current_user.
1800 * The result is a boolean value: true if user has the indicated
1801 * privilege, false if not.
1805 * has_function_privilege_name_name
1806 * Check user privileges on a function given
1807 * name username, text functionname, and text priv name.
1810 has_function_privilege_name_name(PG_FUNCTION_ARGS)
1812 Name username = PG_GETARG_NAME(0);
1813 text *functionname = PG_GETARG_TEXT_P(1);
1814 text *priv_type_text = PG_GETARG_TEXT_P(2);
1818 AclResult aclresult;
1820 roleid = get_roleid_checked(NameStr(*username));
1821 functionoid = convert_function_name(functionname);
1822 mode = convert_function_priv_string(priv_type_text);
1824 aclresult = pg_proc_aclcheck(functionoid, roleid, mode);
1826 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1830 * has_function_privilege_name
1831 * Check user privileges on a function given
1832 * text functionname and text priv name.
1833 * current_user is assumed
1836 has_function_privilege_name(PG_FUNCTION_ARGS)
1838 text *functionname = PG_GETARG_TEXT_P(0);
1839 text *priv_type_text = PG_GETARG_TEXT_P(1);
1843 AclResult aclresult;
1845 roleid = GetUserId();
1846 functionoid = convert_function_name(functionname);
1847 mode = convert_function_priv_string(priv_type_text);
1849 aclresult = pg_proc_aclcheck(functionoid, roleid, mode);
1851 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1855 * has_function_privilege_name_id
1856 * Check user privileges on a function given
1857 * name usename, function oid, and text priv name.
1860 has_function_privilege_name_id(PG_FUNCTION_ARGS)
1862 Name username = PG_GETARG_NAME(0);
1863 Oid functionoid = PG_GETARG_OID(1);
1864 text *priv_type_text = PG_GETARG_TEXT_P(2);
1867 AclResult aclresult;
1869 roleid = get_roleid_checked(NameStr(*username));
1870 mode = convert_function_priv_string(priv_type_text);
1872 aclresult = pg_proc_aclcheck(functionoid, roleid, mode);
1874 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1878 * has_function_privilege_id
1879 * Check user privileges on a function given
1880 * function oid, and text priv name.
1881 * current_user is assumed
1884 has_function_privilege_id(PG_FUNCTION_ARGS)
1886 Oid functionoid = PG_GETARG_OID(0);
1887 text *priv_type_text = PG_GETARG_TEXT_P(1);
1890 AclResult aclresult;
1892 roleid = GetUserId();
1893 mode = convert_function_priv_string(priv_type_text);
1895 aclresult = pg_proc_aclcheck(functionoid, roleid, mode);
1897 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1901 * has_function_privilege_id_name
1902 * Check user privileges on a function given
1903 * roleid, text functionname, and text priv name.
1906 has_function_privilege_id_name(PG_FUNCTION_ARGS)
1908 Oid roleid = PG_GETARG_OID(0);
1909 text *functionname = PG_GETARG_TEXT_P(1);
1910 text *priv_type_text = PG_GETARG_TEXT_P(2);
1913 AclResult aclresult;
1915 functionoid = convert_function_name(functionname);
1916 mode = convert_function_priv_string(priv_type_text);
1918 aclresult = pg_proc_aclcheck(functionoid, roleid, mode);
1920 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1924 * has_function_privilege_id_id
1925 * Check user privileges on a function given
1926 * roleid, function oid, and text priv name.
1929 has_function_privilege_id_id(PG_FUNCTION_ARGS)
1931 Oid roleid = PG_GETARG_OID(0);
1932 Oid functionoid = PG_GETARG_OID(1);
1933 text *priv_type_text = PG_GETARG_TEXT_P(2);
1935 AclResult aclresult;
1937 mode = convert_function_priv_string(priv_type_text);
1939 aclresult = pg_proc_aclcheck(functionoid, roleid, mode);
1941 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
1945 * Support routines for has_function_privilege family.
1949 * Given a function name expressed as a string, look it up and return Oid
1952 convert_function_name(text *functionname)
1954 char *funcname = text_to_cstring(functionname);
1957 oid = DatumGetObjectId(DirectFunctionCall1(regprocedurein,
1958 CStringGetDatum(funcname)));
1960 if (!OidIsValid(oid))
1962 (errcode(ERRCODE_UNDEFINED_FUNCTION),
1963 errmsg("function \"%s\" does not exist", funcname)));
1969 * convert_function_priv_string
1970 * Convert text string to AclMode value.
1973 convert_function_priv_string(text *priv_type_text)
1975 char *priv_type = text_to_cstring(priv_type_text);
1978 * Return mode from priv_type string
1980 if (pg_strcasecmp(priv_type, "EXECUTE") == 0)
1982 if (pg_strcasecmp(priv_type, "EXECUTE WITH GRANT OPTION") == 0)
1983 return ACL_GRANT_OPTION_FOR(ACL_EXECUTE);
1986 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1987 errmsg("unrecognized privilege type: \"%s\"", priv_type)));
1988 return ACL_NO_RIGHTS; /* keep compiler quiet */
1993 * has_language_privilege variants
1994 * These are all named "has_language_privilege" at the SQL level.
1995 * They take various combinations of language name, language OID,
1996 * user name, user OID, or implicit user = current_user.
1998 * The result is a boolean value: true if user has the indicated
1999 * privilege, false if not.
2003 * has_language_privilege_name_name
2004 * Check user privileges on a language given
2005 * name username, text languagename, and text priv name.
2008 has_language_privilege_name_name(PG_FUNCTION_ARGS)
2010 Name username = PG_GETARG_NAME(0);
2011 text *languagename = PG_GETARG_TEXT_P(1);
2012 text *priv_type_text = PG_GETARG_TEXT_P(2);
2016 AclResult aclresult;
2018 roleid = get_roleid_checked(NameStr(*username));
2019 languageoid = convert_language_name(languagename);
2020 mode = convert_language_priv_string(priv_type_text);
2022 aclresult = pg_language_aclcheck(languageoid, roleid, mode);
2024 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2028 * has_language_privilege_name
2029 * Check user privileges on a language given
2030 * text languagename and text priv name.
2031 * current_user is assumed
2034 has_language_privilege_name(PG_FUNCTION_ARGS)
2036 text *languagename = PG_GETARG_TEXT_P(0);
2037 text *priv_type_text = PG_GETARG_TEXT_P(1);
2041 AclResult aclresult;
2043 roleid = GetUserId();
2044 languageoid = convert_language_name(languagename);
2045 mode = convert_language_priv_string(priv_type_text);
2047 aclresult = pg_language_aclcheck(languageoid, roleid, mode);
2049 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2053 * has_language_privilege_name_id
2054 * Check user privileges on a language given
2055 * name usename, language oid, and text priv name.
2058 has_language_privilege_name_id(PG_FUNCTION_ARGS)
2060 Name username = PG_GETARG_NAME(0);
2061 Oid languageoid = PG_GETARG_OID(1);
2062 text *priv_type_text = PG_GETARG_TEXT_P(2);
2065 AclResult aclresult;
2067 roleid = get_roleid_checked(NameStr(*username));
2068 mode = convert_language_priv_string(priv_type_text);
2070 aclresult = pg_language_aclcheck(languageoid, roleid, mode);
2072 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2076 * has_language_privilege_id
2077 * Check user privileges on a language given
2078 * language oid, and text priv name.
2079 * current_user is assumed
2082 has_language_privilege_id(PG_FUNCTION_ARGS)
2084 Oid languageoid = PG_GETARG_OID(0);
2085 text *priv_type_text = PG_GETARG_TEXT_P(1);
2088 AclResult aclresult;
2090 roleid = GetUserId();
2091 mode = convert_language_priv_string(priv_type_text);
2093 aclresult = pg_language_aclcheck(languageoid, roleid, mode);
2095 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2099 * has_language_privilege_id_name
2100 * Check user privileges on a language given
2101 * roleid, text languagename, and text priv name.
2104 has_language_privilege_id_name(PG_FUNCTION_ARGS)
2106 Oid roleid = PG_GETARG_OID(0);
2107 text *languagename = PG_GETARG_TEXT_P(1);
2108 text *priv_type_text = PG_GETARG_TEXT_P(2);
2111 AclResult aclresult;
2113 languageoid = convert_language_name(languagename);
2114 mode = convert_language_priv_string(priv_type_text);
2116 aclresult = pg_language_aclcheck(languageoid, roleid, mode);
2118 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2122 * has_language_privilege_id_id
2123 * Check user privileges on a language given
2124 * roleid, language oid, and text priv name.
2127 has_language_privilege_id_id(PG_FUNCTION_ARGS)
2129 Oid roleid = PG_GETARG_OID(0);
2130 Oid languageoid = PG_GETARG_OID(1);
2131 text *priv_type_text = PG_GETARG_TEXT_P(2);
2133 AclResult aclresult;
2135 mode = convert_language_priv_string(priv_type_text);
2137 aclresult = pg_language_aclcheck(languageoid, roleid, mode);
2139 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2143 * Support routines for has_language_privilege family.
2147 * Given a language name expressed as a string, look it up and return Oid
2150 convert_language_name(text *languagename)
2152 char *langname = text_to_cstring(languagename);
2155 oid = GetSysCacheOid(LANGNAME,
2156 CStringGetDatum(langname),
2158 if (!OidIsValid(oid))
2160 (errcode(ERRCODE_UNDEFINED_OBJECT),
2161 errmsg("language \"%s\" does not exist", langname)));
2167 * convert_language_priv_string
2168 * Convert text string to AclMode value.
2171 convert_language_priv_string(text *priv_type_text)
2173 char *priv_type = text_to_cstring(priv_type_text);
2176 * Return mode from priv_type string
2178 if (pg_strcasecmp(priv_type, "USAGE") == 0)
2180 if (pg_strcasecmp(priv_type, "USAGE WITH GRANT OPTION") == 0)
2181 return ACL_GRANT_OPTION_FOR(ACL_USAGE);
2184 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2185 errmsg("unrecognized privilege type: \"%s\"", priv_type)));
2186 return ACL_NO_RIGHTS; /* keep compiler quiet */
2191 * has_schema_privilege variants
2192 * These are all named "has_schema_privilege" at the SQL level.
2193 * They take various combinations of schema name, schema OID,
2194 * user name, user OID, or implicit user = current_user.
2196 * The result is a boolean value: true if user has the indicated
2197 * privilege, false if not.
2201 * has_schema_privilege_name_name
2202 * Check user privileges on a schema given
2203 * name username, text schemaname, and text priv name.
2206 has_schema_privilege_name_name(PG_FUNCTION_ARGS)
2208 Name username = PG_GETARG_NAME(0);
2209 text *schemaname = PG_GETARG_TEXT_P(1);
2210 text *priv_type_text = PG_GETARG_TEXT_P(2);
2214 AclResult aclresult;
2216 roleid = get_roleid_checked(NameStr(*username));
2217 schemaoid = convert_schema_name(schemaname);
2218 mode = convert_schema_priv_string(priv_type_text);
2220 aclresult = pg_namespace_aclcheck(schemaoid, roleid, mode);
2222 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2226 * has_schema_privilege_name
2227 * Check user privileges on a schema given
2228 * text schemaname and text priv name.
2229 * current_user is assumed
2232 has_schema_privilege_name(PG_FUNCTION_ARGS)
2234 text *schemaname = PG_GETARG_TEXT_P(0);
2235 text *priv_type_text = PG_GETARG_TEXT_P(1);
2239 AclResult aclresult;
2241 roleid = GetUserId();
2242 schemaoid = convert_schema_name(schemaname);
2243 mode = convert_schema_priv_string(priv_type_text);
2245 aclresult = pg_namespace_aclcheck(schemaoid, roleid, mode);
2247 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2251 * has_schema_privilege_name_id
2252 * Check user privileges on a schema given
2253 * name usename, schema oid, and text priv name.
2256 has_schema_privilege_name_id(PG_FUNCTION_ARGS)
2258 Name username = PG_GETARG_NAME(0);
2259 Oid schemaoid = PG_GETARG_OID(1);
2260 text *priv_type_text = PG_GETARG_TEXT_P(2);
2263 AclResult aclresult;
2265 roleid = get_roleid_checked(NameStr(*username));
2266 mode = convert_schema_priv_string(priv_type_text);
2268 aclresult = pg_namespace_aclcheck(schemaoid, roleid, mode);
2270 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2274 * has_schema_privilege_id
2275 * Check user privileges on a schema given
2276 * schema oid, and text priv name.
2277 * current_user is assumed
2280 has_schema_privilege_id(PG_FUNCTION_ARGS)
2282 Oid schemaoid = PG_GETARG_OID(0);
2283 text *priv_type_text = PG_GETARG_TEXT_P(1);
2286 AclResult aclresult;
2288 roleid = GetUserId();
2289 mode = convert_schema_priv_string(priv_type_text);
2291 aclresult = pg_namespace_aclcheck(schemaoid, roleid, mode);
2293 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2297 * has_schema_privilege_id_name
2298 * Check user privileges on a schema given
2299 * roleid, text schemaname, and text priv name.
2302 has_schema_privilege_id_name(PG_FUNCTION_ARGS)
2304 Oid roleid = PG_GETARG_OID(0);
2305 text *schemaname = PG_GETARG_TEXT_P(1);
2306 text *priv_type_text = PG_GETARG_TEXT_P(2);
2309 AclResult aclresult;
2311 schemaoid = convert_schema_name(schemaname);
2312 mode = convert_schema_priv_string(priv_type_text);
2314 aclresult = pg_namespace_aclcheck(schemaoid, roleid, mode);
2316 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2320 * has_schema_privilege_id_id
2321 * Check user privileges on a schema given
2322 * roleid, schema oid, and text priv name.
2325 has_schema_privilege_id_id(PG_FUNCTION_ARGS)
2327 Oid roleid = PG_GETARG_OID(0);
2328 Oid schemaoid = PG_GETARG_OID(1);
2329 text *priv_type_text = PG_GETARG_TEXT_P(2);
2331 AclResult aclresult;
2333 mode = convert_schema_priv_string(priv_type_text);
2335 aclresult = pg_namespace_aclcheck(schemaoid, roleid, mode);
2337 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2341 * Support routines for has_schema_privilege family.
2345 * Given a schema name expressed as a string, look it up and return Oid
2348 convert_schema_name(text *schemaname)
2350 char *nspname = text_to_cstring(schemaname);
2353 oid = GetSysCacheOid(NAMESPACENAME,
2354 CStringGetDatum(nspname),
2356 if (!OidIsValid(oid))
2358 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2359 errmsg("schema \"%s\" does not exist", nspname)));
2365 * convert_schema_priv_string
2366 * Convert text string to AclMode value.
2369 convert_schema_priv_string(text *priv_type_text)
2371 char *priv_type = text_to_cstring(priv_type_text);
2374 * Return mode from priv_type string
2376 if (pg_strcasecmp(priv_type, "CREATE") == 0)
2378 if (pg_strcasecmp(priv_type, "CREATE WITH GRANT OPTION") == 0)
2379 return ACL_GRANT_OPTION_FOR(ACL_CREATE);
2381 if (pg_strcasecmp(priv_type, "USAGE") == 0)
2383 if (pg_strcasecmp(priv_type, "USAGE WITH GRANT OPTION") == 0)
2384 return ACL_GRANT_OPTION_FOR(ACL_USAGE);
2387 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2388 errmsg("unrecognized privilege type: \"%s\"", priv_type)));
2389 return ACL_NO_RIGHTS; /* keep compiler quiet */
2393 * has_tablespace_privilege variants
2394 * These are all named "has_tablespace_privilege" at the SQL level.
2395 * They take various combinations of tablespace name, tablespace OID,
2396 * user name, user OID, or implicit user = current_user.
2398 * The result is a boolean value: true if user has the indicated
2399 * privilege, false if not.
2403 * has_tablespace_privilege_name_name
2404 * Check user privileges on a tablespace given
2405 * name username, text tablespacename, and text priv name.
2408 has_tablespace_privilege_name_name(PG_FUNCTION_ARGS)
2410 Name username = PG_GETARG_NAME(0);
2411 text *tablespacename = PG_GETARG_TEXT_P(1);
2412 text *priv_type_text = PG_GETARG_TEXT_P(2);
2416 AclResult aclresult;
2418 roleid = get_roleid_checked(NameStr(*username));
2419 tablespaceoid = convert_tablespace_name(tablespacename);
2420 mode = convert_tablespace_priv_string(priv_type_text);
2422 aclresult = pg_tablespace_aclcheck(tablespaceoid, roleid, mode);
2424 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2428 * has_tablespace_privilege_name
2429 * Check user privileges on a tablespace given
2430 * text tablespacename and text priv name.
2431 * current_user is assumed
2434 has_tablespace_privilege_name(PG_FUNCTION_ARGS)
2436 text *tablespacename = PG_GETARG_TEXT_P(0);
2437 text *priv_type_text = PG_GETARG_TEXT_P(1);
2441 AclResult aclresult;
2443 roleid = GetUserId();
2444 tablespaceoid = convert_tablespace_name(tablespacename);
2445 mode = convert_tablespace_priv_string(priv_type_text);
2447 aclresult = pg_tablespace_aclcheck(tablespaceoid, roleid, mode);
2449 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2453 * has_tablespace_privilege_name_id
2454 * Check user privileges on a tablespace given
2455 * name usename, tablespace oid, and text priv name.
2458 has_tablespace_privilege_name_id(PG_FUNCTION_ARGS)
2460 Name username = PG_GETARG_NAME(0);
2461 Oid tablespaceoid = PG_GETARG_OID(1);
2462 text *priv_type_text = PG_GETARG_TEXT_P(2);
2465 AclResult aclresult;
2467 roleid = get_roleid_checked(NameStr(*username));
2468 mode = convert_tablespace_priv_string(priv_type_text);
2470 aclresult = pg_tablespace_aclcheck(tablespaceoid, roleid, mode);
2472 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2476 * has_tablespace_privilege_id
2477 * Check user privileges on a tablespace given
2478 * tablespace oid, and text priv name.
2479 * current_user is assumed
2482 has_tablespace_privilege_id(PG_FUNCTION_ARGS)
2484 Oid tablespaceoid = PG_GETARG_OID(0);
2485 text *priv_type_text = PG_GETARG_TEXT_P(1);
2488 AclResult aclresult;
2490 roleid = GetUserId();
2491 mode = convert_tablespace_priv_string(priv_type_text);
2493 aclresult = pg_tablespace_aclcheck(tablespaceoid, roleid, mode);
2495 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2499 * has_tablespace_privilege_id_name
2500 * Check user privileges on a tablespace given
2501 * roleid, text tablespacename, and text priv name.
2504 has_tablespace_privilege_id_name(PG_FUNCTION_ARGS)
2506 Oid roleid = PG_GETARG_OID(0);
2507 text *tablespacename = PG_GETARG_TEXT_P(1);
2508 text *priv_type_text = PG_GETARG_TEXT_P(2);
2511 AclResult aclresult;
2513 tablespaceoid = convert_tablespace_name(tablespacename);
2514 mode = convert_tablespace_priv_string(priv_type_text);
2516 aclresult = pg_tablespace_aclcheck(tablespaceoid, roleid, mode);
2518 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2522 * has_tablespace_privilege_id_id
2523 * Check user privileges on a tablespace given
2524 * roleid, tablespace oid, and text priv name.
2527 has_tablespace_privilege_id_id(PG_FUNCTION_ARGS)
2529 Oid roleid = PG_GETARG_OID(0);
2530 Oid tablespaceoid = PG_GETARG_OID(1);
2531 text *priv_type_text = PG_GETARG_TEXT_P(2);
2533 AclResult aclresult;
2535 mode = convert_tablespace_priv_string(priv_type_text);
2537 aclresult = pg_tablespace_aclcheck(tablespaceoid, roleid, mode);
2539 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2543 * Support routines for has_tablespace_privilege family.
2547 * Given a tablespace name expressed as a string, look it up and return Oid
2550 convert_tablespace_name(text *tablespacename)
2552 char *spcname = text_to_cstring(tablespacename);
2555 oid = get_tablespace_oid(spcname);
2557 if (!OidIsValid(oid))
2559 (errcode(ERRCODE_UNDEFINED_OBJECT),
2560 errmsg("tablespace \"%s\" does not exist", spcname)));
2566 * convert_tablespace_priv_string
2567 * Convert text string to AclMode value.
2570 convert_tablespace_priv_string(text *priv_type_text)
2572 char *priv_type = text_to_cstring(priv_type_text);
2575 * Return mode from priv_type string
2577 if (pg_strcasecmp(priv_type, "CREATE") == 0)
2579 if (pg_strcasecmp(priv_type, "CREATE WITH GRANT OPTION") == 0)
2580 return ACL_GRANT_OPTION_FOR(ACL_CREATE);
2583 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2584 errmsg("unrecognized privilege type: \"%s\"", priv_type)));
2585 return ACL_NO_RIGHTS; /* keep compiler quiet */
2589 * pg_has_role variants
2590 * These are all named "pg_has_role" at the SQL level.
2591 * They take various combinations of role name, role OID,
2592 * user name, user OID, or implicit user = current_user.
2594 * The result is a boolean value: true if user has the indicated
2595 * privilege, false if not.
2599 * pg_has_role_name_name
2600 * Check user privileges on a role given
2601 * name username, name rolename, and text priv name.
2604 pg_has_role_name_name(PG_FUNCTION_ARGS)
2606 Name username = PG_GETARG_NAME(0);
2607 Name rolename = PG_GETARG_NAME(1);
2608 text *priv_type_text = PG_GETARG_TEXT_P(2);
2612 AclResult aclresult;
2614 roleid = get_roleid_checked(NameStr(*username));
2615 roleoid = get_roleid_checked(NameStr(*rolename));
2616 mode = convert_role_priv_string(priv_type_text);
2618 aclresult = pg_role_aclcheck(roleoid, roleid, mode);
2620 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2625 * Check user privileges on a role given
2626 * name rolename and text priv name.
2627 * current_user is assumed
2630 pg_has_role_name(PG_FUNCTION_ARGS)
2632 Name rolename = PG_GETARG_NAME(0);
2633 text *priv_type_text = PG_GETARG_TEXT_P(1);
2637 AclResult aclresult;
2639 roleid = GetUserId();
2640 roleoid = get_roleid_checked(NameStr(*rolename));
2641 mode = convert_role_priv_string(priv_type_text);
2643 aclresult = pg_role_aclcheck(roleoid, roleid, mode);
2645 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2649 * pg_has_role_name_id
2650 * Check user privileges on a role given
2651 * name usename, role oid, and text priv name.
2654 pg_has_role_name_id(PG_FUNCTION_ARGS)
2656 Name username = PG_GETARG_NAME(0);
2657 Oid roleoid = PG_GETARG_OID(1);
2658 text *priv_type_text = PG_GETARG_TEXT_P(2);
2661 AclResult aclresult;
2663 roleid = get_roleid_checked(NameStr(*username));
2664 mode = convert_role_priv_string(priv_type_text);
2666 aclresult = pg_role_aclcheck(roleoid, roleid, mode);
2668 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2673 * Check user privileges on a role given
2674 * role oid, and text priv name.
2675 * current_user is assumed
2678 pg_has_role_id(PG_FUNCTION_ARGS)
2680 Oid roleoid = PG_GETARG_OID(0);
2681 text *priv_type_text = PG_GETARG_TEXT_P(1);
2684 AclResult aclresult;
2686 roleid = GetUserId();
2687 mode = convert_role_priv_string(priv_type_text);
2689 aclresult = pg_role_aclcheck(roleoid, roleid, mode);
2691 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2695 * pg_has_role_id_name
2696 * Check user privileges on a role given
2697 * roleid, name rolename, and text priv name.
2700 pg_has_role_id_name(PG_FUNCTION_ARGS)
2702 Oid roleid = PG_GETARG_OID(0);
2703 Name rolename = PG_GETARG_NAME(1);
2704 text *priv_type_text = PG_GETARG_TEXT_P(2);
2707 AclResult aclresult;
2709 roleoid = get_roleid_checked(NameStr(*rolename));
2710 mode = convert_role_priv_string(priv_type_text);
2712 aclresult = pg_role_aclcheck(roleoid, roleid, mode);
2714 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2719 * Check user privileges on a role given
2720 * roleid, role oid, and text priv name.
2723 pg_has_role_id_id(PG_FUNCTION_ARGS)
2725 Oid roleid = PG_GETARG_OID(0);
2726 Oid roleoid = PG_GETARG_OID(1);
2727 text *priv_type_text = PG_GETARG_TEXT_P(2);
2729 AclResult aclresult;
2731 mode = convert_role_priv_string(priv_type_text);
2733 aclresult = pg_role_aclcheck(roleoid, roleid, mode);
2735 PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
2739 * Support routines for pg_has_role family.
2743 * convert_role_priv_string
2744 * Convert text string to AclMode value.
2746 * We use USAGE to denote whether the privileges of the role are accessible
2747 * (has_privs), MEMBER to denote is_member, and MEMBER WITH GRANT OPTION
2748 * (or ADMIN OPTION) to denote is_admin. There is no ACL bit corresponding
2749 * to MEMBER so we cheat and use ACL_CREATE for that. This convention
2750 * is shared only with pg_role_aclcheck, below.
2753 convert_role_priv_string(text *priv_type_text)
2755 char *priv_type = text_to_cstring(priv_type_text);
2758 * Return mode from priv_type string
2760 if (pg_strcasecmp(priv_type, "USAGE") == 0)
2762 if (pg_strcasecmp(priv_type, "MEMBER") == 0)
2764 if (pg_strcasecmp(priv_type, "USAGE WITH GRANT OPTION") == 0 ||
2765 pg_strcasecmp(priv_type, "USAGE WITH ADMIN OPTION") == 0 ||
2766 pg_strcasecmp(priv_type, "MEMBER WITH GRANT OPTION") == 0 ||
2767 pg_strcasecmp(priv_type, "MEMBER WITH ADMIN OPTION") == 0)
2768 return ACL_GRANT_OPTION_FOR(ACL_CREATE);
2771 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2772 errmsg("unrecognized privilege type: \"%s\"", priv_type)));
2773 return ACL_NO_RIGHTS; /* keep compiler quiet */
2778 * Quick-and-dirty support for pg_has_role
2781 pg_role_aclcheck(Oid role_oid, Oid roleid, AclMode mode)
2783 if (mode & ACL_GRANT_OPTION_FOR(ACL_CREATE))
2785 if (is_admin_of_role(roleid, role_oid))
2788 if (mode & ACL_CREATE)
2790 if (is_member_of_role(roleid, role_oid))
2793 if (mode & ACL_USAGE)
2795 if (has_privs_of_role(roleid, role_oid))
2798 return ACLCHECK_NO_PRIV;
2803 * initialization function (called by InitPostgres)
2806 initialize_acl(void)
2808 if (!IsBootstrapProcessingMode())
2811 * In normal mode, set a callback on any syscache invalidation of
2812 * pg_auth_members rows
2814 CacheRegisterSyscacheCallback(AUTHMEMROLEMEM,
2815 RoleMembershipCacheCallback,
2821 * RoleMembershipCacheCallback
2822 * Syscache inval callback function
2825 RoleMembershipCacheCallback(Datum arg, int cacheid, ItemPointer tuplePtr)
2827 /* Force membership caches to be recomputed on next use */
2828 cached_privs_role = InvalidOid;
2829 cached_member_role = InvalidOid;
2833 /* Check if specified role has rolinherit set */
2835 has_rolinherit(Oid roleid)
2837 bool result = false;
2840 utup = SearchSysCache(AUTHOID,
2841 ObjectIdGetDatum(roleid),
2843 if (HeapTupleIsValid(utup))
2845 result = ((Form_pg_authid) GETSTRUCT(utup))->rolinherit;
2846 ReleaseSysCache(utup);
2853 * Get a list of roles that the specified roleid has the privileges of
2855 * This is defined not to recurse through roles that don't have rolinherit
2856 * set; for such roles, membership implies the ability to do SET ROLE, but
2857 * the privileges are not available until you've done so.
2859 * Since indirect membership testing is relatively expensive, we cache
2860 * a list of memberships. Hence, the result is only guaranteed good until
2861 * the next call of roles_has_privs_of()!
2863 * For the benefit of select_best_grantor, the result is defined to be
2864 * in breadth-first order, ie, closer relationships earlier.
2867 roles_has_privs_of(Oid roleid)
2871 List *new_cached_privs_roles;
2872 MemoryContext oldctx;
2874 /* If cache is already valid, just return the list */
2875 if (OidIsValid(cached_privs_role) && cached_privs_role == roleid)
2876 return cached_privs_roles;
2879 * Find all the roles that roleid is a member of, including multi-level
2880 * recursion. The role itself will always be the first element of the
2883 * Each element of the list is scanned to see if it adds any indirect
2884 * memberships. We can use a single list as both the record of
2885 * already-found memberships and the agenda of roles yet to be scanned.
2886 * This is a bit tricky but works because the foreach() macro doesn't
2887 * fetch the next list element until the bottom of the loop.
2889 roles_list = list_make1_oid(roleid);
2891 foreach(l, roles_list)
2893 Oid memberid = lfirst_oid(l);
2897 /* Ignore non-inheriting roles */
2898 if (!has_rolinherit(memberid))
2901 /* Find roles that memberid is directly a member of */
2902 memlist = SearchSysCacheList(AUTHMEMMEMROLE, 1,
2903 ObjectIdGetDatum(memberid),
2905 for (i = 0; i < memlist->n_members; i++)
2907 HeapTuple tup = &memlist->members[i]->tuple;
2908 Oid otherid = ((Form_pg_auth_members) GETSTRUCT(tup))->roleid;
2911 * Even though there shouldn't be any loops in the membership
2912 * graph, we must test for having already seen this role. It is
2913 * legal for instance to have both A->B and A->C->B.
2915 roles_list = list_append_unique_oid(roles_list, otherid);
2917 ReleaseSysCacheList(memlist);
2921 * Copy the completed list into TopMemoryContext so it will persist.
2923 oldctx = MemoryContextSwitchTo(TopMemoryContext);
2924 new_cached_privs_roles = list_copy(roles_list);
2925 MemoryContextSwitchTo(oldctx);
2926 list_free(roles_list);
2929 * Now safe to assign to state variable
2931 cached_privs_role = InvalidOid; /* just paranoia */
2932 list_free(cached_privs_roles);
2933 cached_privs_roles = new_cached_privs_roles;
2934 cached_privs_role = roleid;
2936 /* And now we can return the answer */
2937 return cached_privs_roles;
2942 * Get a list of roles that the specified roleid is a member of
2944 * This is defined to recurse through roles regardless of rolinherit.
2946 * Since indirect membership testing is relatively expensive, we cache
2947 * a list of memberships. Hence, the result is only guaranteed good until
2948 * the next call of roles_is_member_of()!
2951 roles_is_member_of(Oid roleid)
2955 List *new_cached_membership_roles;
2956 MemoryContext oldctx;
2958 /* If cache is already valid, just return the list */
2959 if (OidIsValid(cached_member_role) && cached_member_role == roleid)
2960 return cached_membership_roles;
2963 * Find all the roles that roleid is a member of, including multi-level
2964 * recursion. The role itself will always be the first element of the
2967 * Each element of the list is scanned to see if it adds any indirect
2968 * memberships. We can use a single list as both the record of
2969 * already-found memberships and the agenda of roles yet to be scanned.
2970 * This is a bit tricky but works because the foreach() macro doesn't
2971 * fetch the next list element until the bottom of the loop.
2973 roles_list = list_make1_oid(roleid);
2975 foreach(l, roles_list)
2977 Oid memberid = lfirst_oid(l);
2981 /* Find roles that memberid is directly a member of */
2982 memlist = SearchSysCacheList(AUTHMEMMEMROLE, 1,
2983 ObjectIdGetDatum(memberid),
2985 for (i = 0; i < memlist->n_members; i++)
2987 HeapTuple tup = &memlist->members[i]->tuple;
2988 Oid otherid = ((Form_pg_auth_members) GETSTRUCT(tup))->roleid;
2991 * Even though there shouldn't be any loops in the membership
2992 * graph, we must test for having already seen this role. It is
2993 * legal for instance to have both A->B and A->C->B.
2995 roles_list = list_append_unique_oid(roles_list, otherid);
2997 ReleaseSysCacheList(memlist);
3001 * Copy the completed list into TopMemoryContext so it will persist.
3003 oldctx = MemoryContextSwitchTo(TopMemoryContext);
3004 new_cached_membership_roles = list_copy(roles_list);
3005 MemoryContextSwitchTo(oldctx);
3006 list_free(roles_list);
3009 * Now safe to assign to state variable
3011 cached_member_role = InvalidOid; /* just paranoia */
3012 list_free(cached_membership_roles);
3013 cached_membership_roles = new_cached_membership_roles;
3014 cached_member_role = roleid;
3016 /* And now we can return the answer */
3017 return cached_membership_roles;
3022 * Does member have the privileges of role (directly or indirectly)?
3024 * This is defined not to recurse through roles that don't have rolinherit
3025 * set; for such roles, membership implies the ability to do SET ROLE, but
3026 * the privileges are not available until you've done so.
3029 has_privs_of_role(Oid member, Oid role)
3031 /* Fast path for simple case */
3035 /* Superusers have every privilege, so are part of every role */
3036 if (superuser_arg(member))
3040 * Find all the roles that member has the privileges of, including
3041 * multi-level recursion, then see if target role is any one of them.
3043 return list_member_oid(roles_has_privs_of(member), role);
3048 * Is member a member of role (directly or indirectly)?
3050 * This is defined to recurse through roles regardless of rolinherit.
3053 is_member_of_role(Oid member, Oid role)
3055 /* Fast path for simple case */
3059 /* Superusers have every privilege, so are part of every role */
3060 if (superuser_arg(member))
3064 * Find all the roles that member is a member of, including multi-level
3065 * recursion, then see if target role is any one of them.
3067 return list_member_oid(roles_is_member_of(member), role);
3071 * check_is_member_of_role
3072 * is_member_of_role with a standard permission-violation error if not
3075 check_is_member_of_role(Oid member, Oid role)
3077 if (!is_member_of_role(member, role))
3079 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3080 errmsg("must be member of role \"%s\"",
3081 GetUserNameFromId(role))));
3085 * Is member a member of role, not considering superuserness?
3087 * This is identical to is_member_of_role except we ignore superuser
3091 is_member_of_role_nosuper(Oid member, Oid role)
3093 /* Fast path for simple case */
3098 * Find all the roles that member is a member of, including multi-level
3099 * recursion, then see if target role is any one of them.
3101 return list_member_oid(roles_is_member_of(member), role);
3106 * Is member an admin of role (directly or indirectly)? That is, is it
3107 * a member WITH ADMIN OPTION?
3109 * We could cache the result as for is_member_of_role, but currently this
3110 * is not used in any performance-critical paths, so we don't.
3113 is_admin_of_role(Oid member, Oid role)
3115 bool result = false;
3119 /* Fast path for simple case */
3123 /* Superusers have every privilege, so are part of every role */
3124 if (superuser_arg(member))
3128 * Find all the roles that member is a member of, including multi-level
3129 * recursion. We build a list in the same way that is_member_of_role does
3130 * to track visited and unvisited roles.
3132 roles_list = list_make1_oid(member);
3134 foreach(l, roles_list)
3136 Oid memberid = lfirst_oid(l);
3140 /* Find roles that memberid is directly a member of */
3141 memlist = SearchSysCacheList(AUTHMEMMEMROLE, 1,
3142 ObjectIdGetDatum(memberid),
3144 for (i = 0; i < memlist->n_members; i++)
3146 HeapTuple tup = &memlist->members[i]->tuple;
3147 Oid otherid = ((Form_pg_auth_members) GETSTRUCT(tup))->roleid;
3149 if (otherid == role &&
3150 ((Form_pg_auth_members) GETSTRUCT(tup))->admin_option)
3152 /* Found what we came for, so can stop searching */
3157 roles_list = list_append_unique_oid(roles_list, otherid);
3159 ReleaseSysCacheList(memlist);
3164 list_free(roles_list);
3170 /* does what it says ... */
3172 count_one_bits(AclMode mask)
3176 /* this code relies on AclMode being an unsigned type */
3188 * Select the effective grantor ID for a GRANT or REVOKE operation.
3190 * The grantor must always be either the object owner or some role that has
3191 * been explicitly granted grant options. This ensures that all granted
3192 * privileges appear to flow from the object owner, and there are never
3193 * multiple "original sources" of a privilege. Therefore, if the would-be
3194 * grantor is a member of a role that has the needed grant options, we have
3195 * to do the grant as that role instead.
3197 * It is possible that the would-be grantor is a member of several roles
3198 * that have different subsets of the desired grant options, but no one
3199 * role has 'em all. In this case we pick a role with the largest number
3200 * of desired options. Ties are broken in favor of closer ancestors.
3202 * roleId: the role attempting to do the GRANT/REVOKE
3203 * privileges: the privileges to be granted/revoked
3204 * acl: the ACL of the object in question
3205 * ownerId: the role owning the object in question
3206 * *grantorId: receives the OID of the role to do the grant as
3207 * *grantOptions: receives the grant options actually held by grantorId
3209 * If no grant options exist, we set grantorId to roleId, grantOptions to 0.
3212 select_best_grantor(Oid roleId, AclMode privileges,
3213 const Acl *acl, Oid ownerId,
3214 Oid *grantorId, AclMode *grantOptions)
3216 AclMode needed_goptions = ACL_GRANT_OPTION_FOR(privileges);
3222 * The object owner is always treated as having all grant options, so if
3223 * roleId is the owner it's easy. Also, if roleId is a superuser it's
3224 * easy: superusers are implicitly members of every role, so they act as
3227 if (roleId == ownerId || superuser_arg(roleId))
3229 *grantorId = ownerId;
3230 *grantOptions = needed_goptions;
3235 * Otherwise we have to do a careful search to see if roleId has the
3236 * privileges of any suitable role. Note: we can hang onto the result of
3237 * roles_has_privs_of() throughout this loop, because aclmask_direct()
3238 * doesn't query any role memberships.
3240 roles_list = roles_has_privs_of(roleId);
3242 /* initialize candidate result as default */
3243 *grantorId = roleId;
3244 *grantOptions = ACL_NO_RIGHTS;
3247 foreach(l, roles_list)
3249 Oid otherrole = lfirst_oid(l);
3252 otherprivs = aclmask_direct(acl, otherrole, ownerId,
3253 needed_goptions, ACLMASK_ALL);
3254 if (otherprivs == needed_goptions)
3256 /* Found a suitable grantor */
3257 *grantorId = otherrole;
3258 *grantOptions = otherprivs;
3263 * If it has just some of the needed privileges, remember best
3266 if (otherprivs != ACL_NO_RIGHTS)
3268 int nnewrights = count_one_bits(otherprivs);
3270 if (nnewrights > nrights)
3272 *grantorId = otherrole;
3273 *grantOptions = otherprivs;
3274 nrights = nnewrights;