Debian Codegraph @

src/backend/catalog/aclchk.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * aclchk.c
4 * Routines to check access control permissions.
5 *
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/catalog/aclchk.c
12 *
13 * NOTES
14 * See acl.h.
15 *
16 * The xxx_aclmask() functions in this file are wrappers around
17 * acl.c's aclmask() function; see that for basic usage information.
18 * The wrapper functions add object-type-specific lookup capability.
19 * Generally, they will throw error if the object doesn't exist.
20 *
21 * The xxx_aclmask_ext() functions add the ability to not throw
22 * error if the object doesn't exist. If their "is_missing" argument
23 * isn't NULL, then when the object isn't found they will set
24 * *is_missing = true and return zero (no privileges) instead of
25 * throwing an error. Caller must initialize *is_missing = false.
26 *
27 * The xxx_aclcheck() functions are simplified wrappers around the
28 * corresponding xxx_aclmask() functions, simply returning ACLCHECK_OK
29 * if any of the privileges specified in "mode" are held, and otherwise
30 * a suitable error code (in practice, always ACLCHECK_NO_PRIV).
31 * Again, they will throw error if the object doesn't exist.
32 *
33 * The xxx_aclcheck_ext() functions add the ability to not throw
34 * error if the object doesn't exist. Their "is_missing" argument
35 * works similarly to the xxx_aclmask_ext() functions.
36 *
37 *-------------------------------------------------------------------------
38 */
39 #include "postgres.h"
40
41 #include "access/genam.h"
42 #include "access/heapam.h"
43 #include "access/htup_details.h"
44 #include "access/sysattr.h"
45 #include "access/tableam.h"
46 #include "access/xact.h"
47 #include "catalog/binary_upgrade.h"
48 #include "catalog/catalog.h"
49 #include "catalog/dependency.h"
50 #include "catalog/indexing.h"
51 #include "catalog/objectaccess.h"
52 #include "catalog/pg_authid.h"
53 #include "catalog/pg_class.h"
54 #include "catalog/pg_database.h"
55 #include "catalog/pg_default_acl.h"
56 #include "catalog/pg_foreign_data_wrapper.h"
57 #include "catalog/pg_foreign_server.h"
58 #include "catalog/pg_init_privs.h"
59 #include "catalog/pg_language.h"
60 #include "catalog/pg_largeobject.h"
61 #include "catalog/pg_largeobject_metadata.h"
62 #include "catalog/pg_namespace.h"
63 #include "catalog/pg_parameter_acl.h"
64 #include "catalog/pg_proc.h"
65 #include "catalog/pg_tablespace.h"
66 #include "catalog/pg_type.h"
67 #include "commands/dbcommands.h"
68 #include "commands/defrem.h"
69 #include "commands/event_trigger.h"
70 #include "commands/extension.h"
71 #include "commands/proclang.h"
72 #include "commands/tablespace.h"
73 #include "foreign/foreign.h"
74 #include "miscadmin.h"
75 #include "nodes/makefuncs.h"
76 #include "parser/parse_func.h"
77 #include "parser/parse_type.h"
78 #include "storage/lmgr.h"
79 #include "utils/acl.h"
80 #include "utils/aclchk_internal.h"
81 #include "utils/builtins.h"
82 #include "utils/fmgroids.h"
83 #include "utils/guc.h"
84 #include "utils/lsyscache.h"
85 #include "utils/rel.h"
86 #include "utils/syscache.h"
87
88 /*
89 * Internal format used by ALTER DEFAULT PRIVILEGES.
90 */
91 typedef struct
92 {
93 Oid roleid; /* owning role */
94 Oid nspid; /* namespace, or InvalidOid if none */
95 /* remaining fields are same as in InternalGrant: */
96 bool is_grant;
97 ObjectType objtype;
98 bool all_privs;
99 AclMode privileges;
100 List *grantees;
101 bool grant_option;
102 DropBehavior behavior;
103 } InternalDefaultACL;
104
105 /*
106 * When performing a binary-upgrade, pg_dump will call a function to set
107 * this variable to let us know that we need to populate the pg_init_privs
108 * table for the GRANT/REVOKE commands while this variable is set to true.
109 */
110 bool binary_upgrade_record_init_privs = false;
111
112 static void ExecGrantStmt_oids(InternalGrant *istmt);
113 static void ExecGrant_Relation(InternalGrant *istmt);
114 static void ExecGrant_common(InternalGrant *istmt, Oid classid, AclMode default_privs,
115 void (*object_check) (InternalGrant *istmt, HeapTuple tuple));
116 static void ExecGrant_Language_check(InternalGrant *istmt, HeapTuple tuple);
117 static void ExecGrant_Largeobject(InternalGrant *istmt);
118 static void ExecGrant_Type_check(InternalGrant *istmt, HeapTuple tuple);
119 static void ExecGrant_Parameter(InternalGrant *istmt);
120
121 static void SetDefaultACLsInSchemas(InternalDefaultACL *iacls, List *nspnames);
122 static void SetDefaultACL(InternalDefaultACL *iacls);
123
124 static List *objectNamesToOids(ObjectType objtype, List *objnames,
125 bool is_grant);
126 static List *objectsInSchemaToOids(ObjectType objtype, List *nspnames);
127 static List *getRelationsInNamespace(Oid namespaceId, char relkind);
128 static void expand_col_privileges(List *colnames, Oid table_oid,
129 AclMode this_privileges,
130 AclMode *col_privileges,
131 int num_col_privileges);
132 static void expand_all_col_privileges(Oid table_oid, Form_pg_class classForm,
133 AclMode this_privileges,
134 AclMode *col_privileges,
135 int num_col_privileges);
136 static AclMode string_to_privilege(const char *privname);
137 static const char *privilege_to_string(AclMode privilege);
138 static AclMode restrict_and_check_grant(bool is_grant, AclMode avail_goptions,
139 bool all_privs, AclMode privileges,
140 Oid objectId, Oid grantorId,
141 ObjectType objtype, const char *objname,
142 AttrNumber att_number, const char *colname);
143 static AclMode pg_aclmask(ObjectType objtype, Oid object_oid, AttrNumber attnum,
144 Oid roleid, AclMode mask, AclMaskHow how);
145 static AclMode object_aclmask(Oid classid, Oid objectid, Oid roleid,
146 AclMode mask, AclMaskHow how);
147 static AclMode object_aclmask_ext(Oid classid, Oid objectid, Oid roleid,
148 AclMode mask, AclMaskHow how,
149 bool *is_missing);
150 static AclMode pg_attribute_aclmask(Oid table_oid, AttrNumber attnum,
151 Oid roleid, AclMode mask, AclMaskHow how);
152 static AclMode pg_attribute_aclmask_ext(Oid table_oid, AttrNumber attnum,
153 Oid roleid, AclMode mask,
154 AclMaskHow how, bool *is_missing);
155 static AclMode pg_class_aclmask_ext(Oid table_oid, Oid roleid,
156 AclMode mask, AclMaskHow how,
157 bool *is_missing);
158 static AclMode pg_parameter_acl_aclmask(Oid acl_oid, Oid roleid,
159 AclMode mask, AclMaskHow how);
160 static AclMode pg_largeobject_aclmask_snapshot(Oid lobj_oid, Oid roleid,
161 AclMode mask, AclMaskHow how, Snapshot snapshot);
162 static AclMode pg_namespace_aclmask_ext(Oid nsp_oid, Oid roleid,
163 AclMode mask, AclMaskHow how,
164 bool *is_missing);
165 static AclMode pg_type_aclmask_ext(Oid type_oid, Oid roleid,
166 AclMode mask, AclMaskHow how,
167 bool *is_missing);
168 static void recordExtensionInitPriv(Oid objoid, Oid classoid, int objsubid,
169 Acl *new_acl);
170 static void recordExtensionInitPrivWorker(Oid objoid, Oid classoid, int objsubid,
171 Acl *new_acl);
172
173
174 /*
175 * If is_grant is true, adds the given privileges for the list of
176 * grantees to the existing old_acl. If is_grant is false, the
177 * privileges for the given grantees are removed from old_acl.
178 *
179 * NB: the original old_acl is pfree'd.
180 */
181 static Acl *
182 merge_acl_with_grant(Acl *old_acl, bool is_grant,
183 bool grant_option, DropBehavior behavior,
184 List *grantees, AclMode privileges,
185 Oid grantorId, Oid ownerId)
186 {
187 unsigned modechg;
188 ListCell *j;
189 Acl *new_acl;
190
191 modechg = is_grant ? ACL_MODECHG_ADD : ACL_MODECHG_DEL;
192
193 new_acl = old_acl;
194
195 foreach(j, grantees)
196 {
197 AclItem aclitem;
198 Acl *newer_acl;
199
200 aclitem.ai_grantee = lfirst_oid(j);
201
202 /*
203 * Grant options can only be granted to individual roles, not PUBLIC.
204 * The reason is that if a user would re-grant a privilege that he
205 * held through PUBLIC, and later the user is removed, the situation
206 * is impossible to clean up.
207 */
208 if (is_grant && grant_option && aclitem.ai_grantee == ACL_ID_PUBLIC)
209 ereport(ERROR,
210 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
211 errmsg("grant options can only be granted to roles")));
212
213 aclitem.ai_grantor = grantorId;
214
215 /*
216 * The asymmetry in the conditions here comes from the spec. In
217 * GRANT, the grant_option flag signals WITH GRANT OPTION, which means
218 * to grant both the basic privilege and its grant option. But in
219 * REVOKE, plain revoke revokes both the basic privilege and its grant
220 * option, while REVOKE GRANT OPTION revokes only the option.
221 */
222 ACLITEM_SET_PRIVS_GOPTIONS(aclitem,
223 (is_grant || !grant_option) ? privileges : ACL_NO_RIGHTS,
224 (!is_grant || grant_option) ? privileges : ACL_NO_RIGHTS);
225
226 newer_acl = aclupdate(new_acl, &aclitem, modechg, ownerId, behavior);
227
228 /* avoid memory leak when there are many grantees */
229 pfree(new_acl);
230 new_acl = newer_acl;
231 }
232
233 return new_acl;
234 }
235
236 /*
237 * Restrict the privileges to what we can actually grant, and emit
238 * the standards-mandated warning and error messages.
239 */
240 static AclMode
241 restrict_and_check_grant(bool is_grant, AclMode avail_goptions, bool all_privs,
242 AclMode privileges, Oid objectId, Oid grantorId,
243 ObjectType objtype, const char *objname,
244 AttrNumber att_number, const char *colname)
245 {
246 AclMode this_privileges;
247 AclMode whole_mask;
248
249 switch (objtype)
250 {
251 case OBJECT_COLUMN:
252 whole_mask = ACL_ALL_RIGHTS_COLUMN;
253 break;
254 case OBJECT_TABLE:
255 whole_mask = ACL_ALL_RIGHTS_RELATION;
256 break;
257 case OBJECT_SEQUENCE:
258 whole_mask = ACL_ALL_RIGHTS_SEQUENCE;
259 break;
260 case OBJECT_DATABASE:
261 whole_mask = ACL_ALL_RIGHTS_DATABASE;
262 break;
263 case OBJECT_FUNCTION:
264 whole_mask = ACL_ALL_RIGHTS_FUNCTION;
265 break;
266 case OBJECT_LANGUAGE:
267 whole_mask = ACL_ALL_RIGHTS_LANGUAGE;
268 break;
269 case OBJECT_LARGEOBJECT:
270 whole_mask = ACL_ALL_RIGHTS_LARGEOBJECT;
271 break;
272 case OBJECT_SCHEMA:
273 whole_mask = ACL_ALL_RIGHTS_SCHEMA;
274 break;
275 case OBJECT_TABLESPACE:
276 whole_mask = ACL_ALL_RIGHTS_TABLESPACE;
277 break;
278 case OBJECT_FDW:
279 whole_mask = ACL_ALL_RIGHTS_FDW;
280 break;
281 case OBJECT_FOREIGN_SERVER:
282 whole_mask = ACL_ALL_RIGHTS_FOREIGN_SERVER;
283 break;
284 case OBJECT_EVENT_TRIGGER:
285 elog(ERROR, "grantable rights not supported for event triggers");
286 /* not reached, but keep compiler quiet */
287 return ACL_NO_RIGHTS;
288 case OBJECT_TYPE:
289 whole_mask = ACL_ALL_RIGHTS_TYPE;
290 break;
291 case OBJECT_PARAMETER_ACL:
292 whole_mask = ACL_ALL_RIGHTS_PARAMETER_ACL;
293 break;
294 default:
295 elog(ERROR, "unrecognized object type: %d", objtype);
296 /* not reached, but keep compiler quiet */
297 return ACL_NO_RIGHTS;
298 }
299
300 /*
301 * If we found no grant options, consider whether to issue a hard error.
302 * Per spec, having any privilege at all on the object will get you by
303 * here.
304 */
305 if (avail_goptions == ACL_NO_RIGHTS)
306 {
307 if (pg_aclmask(objtype, objectId, att_number, grantorId,
308 whole_mask | ACL_GRANT_OPTION_FOR(whole_mask),
309 ACLMASK_ANY) == ACL_NO_RIGHTS)
310 {
311 if (objtype == OBJECT_COLUMN && colname)
312 aclcheck_error_col(ACLCHECK_NO_PRIV, objtype, objname, colname);
313 else
314 aclcheck_error(ACLCHECK_NO_PRIV, objtype, objname);
315 }
316 }
317
318 /*
319 * Restrict the operation to what we can actually grant or revoke, and
320 * issue a warning if appropriate. (For REVOKE this isn't quite what the
321 * spec says to do: the spec seems to want a warning only if no privilege
322 * bits actually change in the ACL. In practice that behavior seems much
323 * too noisy, as well as inconsistent with the GRANT case.)
324 */
325 this_privileges = privileges & ACL_OPTION_TO_PRIVS(avail_goptions);
326 if (is_grant)
327 {
328 if (this_privileges == 0)
329 {
330 if (objtype == OBJECT_COLUMN && colname)
331 ereport(WARNING,
332 (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED),
333 errmsg("no privileges were granted for column \"%s\" of relation \"%s\"",
334 colname, objname)));
335 else
336 ereport(WARNING,
337 (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED),
338 errmsg("no privileges were granted for \"%s\"",
339 objname)));
340 }
341 else if (!all_privs && this_privileges != privileges)
342 {
343 if (objtype == OBJECT_COLUMN && colname)
344 ereport(WARNING,
345 (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED),
346 errmsg("not all privileges were granted for column \"%s\" of relation \"%s\"",
347 colname, objname)));
348 else
349 ereport(WARNING,
350 (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED),
351 errmsg("not all privileges were granted for \"%s\"",
352 objname)));
353 }
354 }
355 else
356 {
357 if (this_privileges == 0)
358 {
359 if (objtype == OBJECT_COLUMN && colname)
360 ereport(WARNING,
361 (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
362 errmsg("no privileges could be revoked for column \"%s\" of relation \"%s\"",
363 colname, objname)));
364 else
365 ereport(WARNING,
366 (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
367 errmsg("no privileges could be revoked for \"%s\"",
368 objname)));
369 }
370 else if (!all_privs && this_privileges != privileges)
371 {
372 if (objtype == OBJECT_COLUMN && colname)
373 ereport(WARNING,
374 (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
375 errmsg("not all privileges could be revoked for column \"%s\" of relation \"%s\"",
376 colname, objname)));
377 else
378 ereport(WARNING,
379 (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
380 errmsg("not all privileges could be revoked for \"%s\"",
381 objname)));
382 }
383 }
384
385 return this_privileges;
386 }
387
388 /*
389 * Called to execute the utility commands GRANT and REVOKE
390 */
391 void
392 ExecuteGrantStmt(GrantStmt *stmt)
393 {
394 InternalGrant istmt;
395 ListCell *cell;
396 const char *errormsg;
397 AclMode all_privileges;
398
399 if (stmt->grantor)
400 {
401 Oid grantor;
402
403 grantor = get_rolespec_oid(stmt->grantor, false);
404
405 /*
406 * Currently, this clause is only for SQL compatibility, not very
407 * interesting otherwise.
408 */
409 if (grantor != GetUserId())
410 ereport(ERROR,
411 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
412 errmsg("grantor must be current user")));
413 }
414
415 /*
416 * Turn the regular GrantStmt into the InternalGrant form.
417 */
418 istmt.is_grant = stmt->is_grant;
419 istmt.objtype = stmt->objtype;
420
421 /* Collect the OIDs of the target objects */
422 switch (stmt->targtype)
423 {
424 case ACL_TARGET_OBJECT:
425 istmt.objects = objectNamesToOids(stmt->objtype, stmt->objects,
426 stmt->is_grant);
427 break;
428 case ACL_TARGET_ALL_IN_SCHEMA:
429 istmt.objects = objectsInSchemaToOids(stmt->objtype, stmt->objects);
430 break;
431 /* ACL_TARGET_DEFAULTS should not be seen here */
432 default:
433 elog(ERROR, "unrecognized GrantStmt.targtype: %d",
434 (int) stmt->targtype);
435 }
436
437 /* all_privs to be filled below */
438 /* privileges to be filled below */
439 istmt.col_privs = NIL; /* may get filled below */
440 istmt.grantees = NIL; /* filled below */
441 istmt.grant_option = stmt->grant_option;
442 istmt.behavior = stmt->behavior;
443
444 /*
445 * Convert the RoleSpec list into an Oid list. Note that at this point we
446 * insert an ACL_ID_PUBLIC into the list if appropriate, so downstream
447 * there shouldn't be any additional work needed to support this case.
448 */
449 foreach(cell, stmt->grantees)
450 {
451 RoleSpec *grantee = (RoleSpec *) lfirst(cell);
452 Oid grantee_uid;
453
454 switch (grantee->roletype)
455 {
456 case ROLESPEC_PUBLIC:
457 grantee_uid = ACL_ID_PUBLIC;
458 break;
459 default:
460 grantee_uid = get_rolespec_oid(grantee, false);
461 break;
462 }
463 istmt.grantees = lappend_oid(istmt.grantees, grantee_uid);
464 }
465
466 /*
467 * Convert stmt->privileges, a list of AccessPriv nodes, into an AclMode
468 * bitmask. Note: objtype can't be OBJECT_COLUMN.
469 */
470 switch (stmt->objtype)
471 {
472 case OBJECT_TABLE:
473
474 /*
475 * Because this might be a sequence, we test both relation and
476 * sequence bits, and later do a more limited test when we know
477 * the object type.
478 */
479 all_privileges = ACL_ALL_RIGHTS_RELATION | ACL_ALL_RIGHTS_SEQUENCE;
480 errormsg = gettext_noop("invalid privilege type %s for relation");
481 break;
482 case OBJECT_SEQUENCE:
483 all_privileges = ACL_ALL_RIGHTS_SEQUENCE;
484 errormsg = gettext_noop("invalid privilege type %s for sequence");
485 break;
486 case OBJECT_DATABASE:
487 all_privileges = ACL_ALL_RIGHTS_DATABASE;
488 errormsg = gettext_noop("invalid privilege type %s for database");
489 break;
490 case OBJECT_DOMAIN:
491 all_privileges = ACL_ALL_RIGHTS_TYPE;
492 errormsg = gettext_noop("invalid privilege type %s for domain");
493 break;
494 case OBJECT_FUNCTION:
495 all_privileges = ACL_ALL_RIGHTS_FUNCTION;
496 errormsg = gettext_noop("invalid privilege type %s for function");
497 break;
498 case OBJECT_LANGUAGE:
499 all_privileges = ACL_ALL_RIGHTS_LANGUAGE;
500 errormsg = gettext_noop("invalid privilege type %s for language");
501 break;
502 case OBJECT_LARGEOBJECT:
503 all_privileges = ACL_ALL_RIGHTS_LARGEOBJECT;
504 errormsg = gettext_noop("invalid privilege type %s for large object");
505 break;
506 case OBJECT_SCHEMA:
507 all_privileges = ACL_ALL_RIGHTS_SCHEMA;
508 errormsg = gettext_noop("invalid privilege type %s for schema");
509 break;
510 case OBJECT_PROCEDURE:
511 all_privileges = ACL_ALL_RIGHTS_FUNCTION;
512 errormsg = gettext_noop("invalid privilege type %s for procedure");
513 break;
514 case OBJECT_ROUTINE:
515 all_privileges = ACL_ALL_RIGHTS_FUNCTION;
516 errormsg = gettext_noop("invalid privilege type %s for routine");
517 break;
518 case OBJECT_TABLESPACE:
519 all_privileges = ACL_ALL_RIGHTS_TABLESPACE;
520 errormsg = gettext_noop("invalid privilege type %s for tablespace");
521 break;
522 case OBJECT_TYPE:
523 all_privileges = ACL_ALL_RIGHTS_TYPE;
524 errormsg = gettext_noop("invalid privilege type %s for type");
525 break;
526 case OBJECT_FDW:
527 all_privileges = ACL_ALL_RIGHTS_FDW;
528 errormsg = gettext_noop("invalid privilege type %s for foreign-data wrapper");
529 break;
530 case OBJECT_FOREIGN_SERVER:
531 all_privileges = ACL_ALL_RIGHTS_FOREIGN_SERVER;
532 errormsg = gettext_noop("invalid privilege type %s for foreign server");
533 break;
534 case OBJECT_PARAMETER_ACL:
535 all_privileges = ACL_ALL_RIGHTS_PARAMETER_ACL;
536 errormsg = gettext_noop("invalid privilege type %s for parameter");
537 break;
538 default:
539 elog(ERROR, "unrecognized GrantStmt.objtype: %d",
540 (int) stmt->objtype);
541 /* keep compiler quiet */
542 all_privileges = ACL_NO_RIGHTS;
543 errormsg = NULL;
544 }
545
546 if (stmt->privileges == NIL)
547 {
548 istmt.all_privs = true;
549
550 /*
551 * will be turned into ACL_ALL_RIGHTS_* by the internal routines
552 * depending on the object type
553 */
554 istmt.privileges = ACL_NO_RIGHTS;
555 }
556 else
557 {
558 istmt.all_privs = false;
559 istmt.privileges = ACL_NO_RIGHTS;
560
561 foreach(cell, stmt->privileges)
562 {
563 AccessPriv *privnode = (AccessPriv *) lfirst(cell);
564 AclMode priv;
565
566 /*
567 * If it's a column-level specification, we just set it aside in
568 * col_privs for the moment; but insist it's for a relation.
569 */
570 if (privnode->cols)
571 {
572 if (stmt->objtype != OBJECT_TABLE)
573 ereport(ERROR,
574 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
575 errmsg("column privileges are only valid for relations")));
576 istmt.col_privs = lappend(istmt.col_privs, privnode);
577 continue;
578 }
579
580 if (privnode->priv_name == NULL) /* parser mistake? */
581 elog(ERROR, "AccessPriv node must specify privilege or columns");
582 priv = string_to_privilege(privnode->priv_name);
583
584 if (priv & ~((AclMode) all_privileges))
585 ereport(ERROR,
586 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
587 errmsg(errormsg, privilege_to_string(priv))));
588
589 istmt.privileges |= priv;
590 }
591 }
592
593 ExecGrantStmt_oids(&istmt);
594 }
595
596 /*
597 * ExecGrantStmt_oids
598 *
599 * Internal entry point for granting and revoking privileges.
600 */
601 static void
602 ExecGrantStmt_oids(InternalGrant *istmt)
603 {
604 switch (istmt->objtype)
605 {
606 case OBJECT_TABLE:
607 case OBJECT_SEQUENCE:
608 ExecGrant_Relation(istmt);
609 break;
610 case OBJECT_DATABASE:
611 ExecGrant_common(istmt, DatabaseRelationId, ACL_ALL_RIGHTS_DATABASE, NULL);
612 break;
613 case OBJECT_DOMAIN:
614 case OBJECT_TYPE:
615 ExecGrant_common(istmt, TypeRelationId, ACL_ALL_RIGHTS_TYPE, ExecGrant_Type_check);
616 break;
617 case OBJECT_FDW:
618 ExecGrant_common(istmt, ForeignDataWrapperRelationId, ACL_ALL_RIGHTS_FDW, NULL);
619 break;
620 case OBJECT_FOREIGN_SERVER:
621 ExecGrant_common(istmt, ForeignServerRelationId, ACL_ALL_RIGHTS_FOREIGN_SERVER, NULL);
622 break;
623 case OBJECT_FUNCTION:
624 case OBJECT_PROCEDURE:
625 case OBJECT_ROUTINE:
626 ExecGrant_common(istmt, ProcedureRelationId, ACL_ALL_RIGHTS_FUNCTION, NULL);
627 break;
628 case OBJECT_LANGUAGE:
629 ExecGrant_common(istmt, LanguageRelationId, ACL_ALL_RIGHTS_LANGUAGE, ExecGrant_Language_check);
630 break;
631 case OBJECT_LARGEOBJECT:
632 ExecGrant_Largeobject(istmt);
633 break;
634 case OBJECT_SCHEMA:
635 ExecGrant_common(istmt, NamespaceRelationId, ACL_ALL_RIGHTS_SCHEMA, NULL);
636 break;
637 case OBJECT_TABLESPACE:
638 ExecGrant_common(istmt, TableSpaceRelationId, ACL_ALL_RIGHTS_TABLESPACE, NULL);
639 break;
640 case OBJECT_PARAMETER_ACL:
641 ExecGrant_Parameter(istmt);
642 break;
643 default:
644 elog(ERROR, "unrecognized GrantStmt.objtype: %d",
645 (int) istmt->objtype);
646 }
647
648 /*
649 * Pass the info to event triggers about the just-executed GRANT. Note
650 * that we prefer to do it after actually executing it, because that gives
651 * the functions a chance to adjust the istmt with privileges actually
652 * granted.
653 */
654 if (EventTriggerSupportsObjectType(istmt->objtype))
655 EventTriggerCollectGrant(istmt);
656 }
657
658 /*
659 * objectNamesToOids
660 *
661 * Turn a list of object names of a given type into an Oid list.
662 *
663 * XXX This function intentionally takes only an AccessShareLock. In the face
664 * of concurrent DDL, we might easily latch onto an old version of an object,
665 * causing the GRANT or REVOKE statement to fail. But it does prevent the
666 * object from disappearing altogether. To do better, we would need to use a
667 * self-exclusive lock, perhaps ShareUpdateExclusiveLock, here and before
668 * *every* CatalogTupleUpdate() of a row that GRANT/REVOKE can affect.
669 * Besides that additional work, this could have operational costs. For
670 * example, it would make GRANT ALL TABLES IN SCHEMA terminate every
671 * autovacuum running in the schema and consume a shared lock table entry per
672 * table in the schema. The user-visible benefit of that additional work is
673 * just changing "ERROR: tuple concurrently updated" to blocking. That's not
674 * nothing, but it might not outweigh autovacuum termination and lock table
675 * consumption spikes.
676 */
677 static List *
678 objectNamesToOids(ObjectType objtype, List *objnames, bool is_grant)
679 {
680 List *objects = NIL;
681 ListCell *cell;
682 const LOCKMODE lockmode = AccessShareLock;
683
684 Assert(objnames != NIL);
685
686 switch (objtype)
687 {
688 default:
689
690 /*
691 * For most object types, we use get_object_address() directly.
692 */
693 foreach(cell, objnames)
694 {
695 ObjectAddress address;
696
697 address = get_object_address(objtype, lfirst(cell), NULL, lockmode, false);
698 objects = lappend_oid(objects, address.objectId);
699 }
700 break;
701
702 case OBJECT_TABLE:
703 case OBJECT_SEQUENCE:
704
705 /*
706 * Here, we don't use get_object_address(). It requires that the
707 * specified object type match the actual type of the object, but
708 * in GRANT/REVOKE, all table-like things are addressed as TABLE.
709 */
710 foreach(cell, objnames)
711 {
712 RangeVar *relvar = (RangeVar *) lfirst(cell);
713 Oid relOid;
714
715 relOid = RangeVarGetRelid(relvar, lockmode, false);
716 objects = lappend_oid(objects, relOid);
717 }
718 break;
719
720 case OBJECT_DOMAIN:
721 case OBJECT_TYPE:
722
723 /*
724 * The parse representation of types and domains in privilege
725 * targets is different from that expected by get_object_address()
726 * (for parse conflict reasons), so we have to do a bit of
727 * conversion here.
728 */
729 foreach(cell, objnames)
730 {
731 List *typname = (List *) lfirst(cell);
732 TypeName *tn = makeTypeNameFromNameList(typname);
733 ObjectAddress address;
734 Relation relation;
735
736 address = get_object_address(objtype, (Node *) tn, &relation, lockmode, false);
737 Assert(relation == NULL);
738 objects = lappend_oid(objects, address.objectId);
739 }
740 break;
741
742 case OBJECT_PARAMETER_ACL:
743
744 /*
745 * Parameters are handled completely differently.
746 */
747 foreach(cell, objnames)
748 {
749 /*
750 * In this code we represent a GUC by the OID of its entry in
751 * pg_parameter_acl, which we have to manufacture here if it
752 * doesn't exist yet. (That's a hack for sure, but it avoids
753 * messing with all the GRANT/REVOKE infrastructure that
754 * expects to use OIDs for object identities.) However, if
755 * this is a REVOKE, we can instead just ignore any GUCs that
756 * don't have such an entry, as they must not have any
757 * privileges needing removal.
758 */
759 char *parameter = strVal(lfirst(cell));
760 Oid parameterId = ParameterAclLookup(parameter, true);
761
762 if (!OidIsValid(parameterId) && is_grant)
763 {
764 parameterId = ParameterAclCreate(parameter);
765
766 /*
767 * Prevent error when processing duplicate objects, and
768 * make this new entry visible so that ExecGrant_Parameter
769 * can update it.
770 */
771 CommandCounterIncrement();
772 }
773 if (OidIsValid(parameterId))
774 objects = lappend_oid(objects, parameterId);
775 }
776 break;
777 }
778
779 return objects;
780 }
781
782 /*
783 * objectsInSchemaToOids
784 *
785 * Find all objects of a given type in specified schemas, and make a list
786 * of their Oids. We check USAGE privilege on the schemas, but there is
787 * no privilege checking on the individual objects here.
788 */
789 static List *
790 objectsInSchemaToOids(ObjectType objtype, List *nspnames)
791 {
792 List *objects = NIL;
793 ListCell *cell;
794
795 foreach(cell, nspnames)
796 {
797 char *nspname = strVal(lfirst(cell));
798 Oid namespaceId;
799 List *objs;
800
801 namespaceId = LookupExplicitNamespace(nspname, false);
802
803 switch (objtype)
804 {
805 case OBJECT_TABLE:
806 objs = getRelationsInNamespace(namespaceId, RELKIND_RELATION);
807 objects = list_concat(objects, objs);
808 objs = getRelationsInNamespace(namespaceId, RELKIND_VIEW);
809 objects = list_concat(objects, objs);
810 objs = getRelationsInNamespace(namespaceId, RELKIND_MATVIEW);
811 objects = list_concat(objects, objs);
812 objs = getRelationsInNamespace(namespaceId, RELKIND_FOREIGN_TABLE);
813 objects = list_concat(objects, objs);
814 objs = getRelationsInNamespace(namespaceId, RELKIND_PARTITIONED_TABLE);
815 objects = list_concat(objects, objs);
816 break;
817 case OBJECT_SEQUENCE:
818 objs = getRelationsInNamespace(namespaceId, RELKIND_SEQUENCE);
819 objects = list_concat(objects, objs);
820 break;
821 case OBJECT_FUNCTION:
822 case OBJECT_PROCEDURE:
823 case OBJECT_ROUTINE:
824 {
825 ScanKeyData key[2];
826 int keycount;
827 Relation rel;
828 TableScanDesc scan;
829 HeapTuple tuple;
830
831 keycount = 0;
832 ScanKeyInit(&key[keycount++],
833 Anum_pg_proc_pronamespace,
834 BTEqualStrategyNumber, F_OIDEQ,
835 ObjectIdGetDatum(namespaceId));
836
837 if (objtype == OBJECT_FUNCTION)
838 /* includes aggregates and window functions */
839 ScanKeyInit(&key[keycount++],
840 Anum_pg_proc_prokind,
841 BTEqualStrategyNumber, F_CHARNE,
842 CharGetDatum(PROKIND_PROCEDURE));
843 else if (objtype == OBJECT_PROCEDURE)
844 ScanKeyInit(&key[keycount++],
845 Anum_pg_proc_prokind,
846 BTEqualStrategyNumber, F_CHAREQ,
847 CharGetDatum(PROKIND_PROCEDURE));
848
849 rel = table_open(ProcedureRelationId, AccessShareLock);
850 scan = table_beginscan_catalog(rel, keycount, key);
851
852 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
853 {
854 Oid oid = ((Form_pg_proc) GETSTRUCT(tuple))->oid;
855
856 objects = lappend_oid(objects, oid);
857 }
858
859 table_endscan(scan);
860 table_close(rel, AccessShareLock);
861 }
862 break;
863 default:
864 /* should not happen */
865 elog(ERROR, "unrecognized GrantStmt.objtype: %d",
866 (int) objtype);
867 }
868 }
869
870 return objects;
871 }
872
873 /*
874 * getRelationsInNamespace
875 *
876 * Return Oid list of relations in given namespace filtered by relation kind
877 */
878 static List *
879 getRelationsInNamespace(Oid namespaceId, char relkind)
880 {
881 List *relations = NIL;
882 ScanKeyData key[2];
883 Relation rel;
884 TableScanDesc scan;
885 HeapTuple tuple;
886
887 ScanKeyInit(&key[0],
888 Anum_pg_class_relnamespace,
889 BTEqualStrategyNumber, F_OIDEQ,
890 ObjectIdGetDatum(namespaceId));
891 ScanKeyInit(&key[1],
892 Anum_pg_class_relkind,
893 BTEqualStrategyNumber, F_CHAREQ,
894 CharGetDatum(relkind));
895
896 rel = table_open(RelationRelationId, AccessShareLock);
897 scan = table_beginscan_catalog(rel, 2, key);
898
899 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
900 {
901 Oid oid = ((Form_pg_class) GETSTRUCT(tuple))->oid;
902
903 relations = lappend_oid(relations, oid);
904 }
905
906 table_endscan(scan);
907 table_close(rel, AccessShareLock);
908
909 return relations;
910 }
911
912
913 /*
914 * ALTER DEFAULT PRIVILEGES statement
915 */
916 void
917 ExecAlterDefaultPrivilegesStmt(ParseState *pstate, AlterDefaultPrivilegesStmt *stmt)
918 {
919 GrantStmt *action = stmt->action;
920 InternalDefaultACL iacls;
921 ListCell *cell;
922 List *rolespecs = NIL;
923 List *nspnames = NIL;
924 DefElem *drolespecs = NULL;
925 DefElem *dnspnames = NULL;
926 AclMode all_privileges;
927 const char *errormsg;
928
929 /* Deconstruct the "options" part of the statement */
930 foreach(cell, stmt->options)
931 {
932 DefElem *defel = (DefElem *) lfirst(cell);
933
934 if (strcmp(defel->defname, "schemas") == 0)
935 {
936 if (dnspnames)
937 errorConflictingDefElem(defel, pstate);
938 dnspnames = defel;
939 }
940 else if (strcmp(defel->defname, "roles") == 0)
941 {
942 if (drolespecs)
943 errorConflictingDefElem(defel, pstate);
944 drolespecs = defel;
945 }
946 else
947 elog(ERROR, "option \"%s\" not recognized", defel->defname);
948 }
949
950 if (dnspnames)
951 nspnames = (List *) dnspnames->arg;
952 if (drolespecs)
953 rolespecs = (List *) drolespecs->arg;
954
955 /* Prepare the InternalDefaultACL representation of the statement */
956 /* roleid to be filled below */
957 /* nspid to be filled in SetDefaultACLsInSchemas */
958 iacls.is_grant = action->is_grant;
959 iacls.objtype = action->objtype;
960 /* all_privs to be filled below */
961 /* privileges to be filled below */
962 iacls.grantees = NIL; /* filled below */
963 iacls.grant_option = action->grant_option;
964 iacls.behavior = action->behavior;
965
966 /*
967 * Convert the RoleSpec list into an Oid list. Note that at this point we
968 * insert an ACL_ID_PUBLIC into the list if appropriate, so downstream
969 * there shouldn't be any additional work needed to support this case.
970 */
971 foreach(cell, action->grantees)
972 {
973 RoleSpec *grantee = (RoleSpec *) lfirst(cell);
974 Oid grantee_uid;
975
976 switch (grantee->roletype)
977 {
978 case ROLESPEC_PUBLIC:
979 grantee_uid = ACL_ID_PUBLIC;
980 break;
981 default:
982 grantee_uid = get_rolespec_oid(grantee, false);
983 break;
984 }
985 iacls.grantees = lappend_oid(iacls.grantees, grantee_uid);
986 }
987
988 /*
989 * Convert action->privileges, a list of privilege strings, into an
990 * AclMode bitmask.
991 */
992 switch (action->objtype)
993 {
994 case OBJECT_TABLE:
995 all_privileges = ACL_ALL_RIGHTS_RELATION;
996 errormsg = gettext_noop("invalid privilege type %s for relation");
997 break;
998 case OBJECT_SEQUENCE:
999 all_privileges = ACL_ALL_RIGHTS_SEQUENCE;
1000 errormsg = gettext_noop("invalid privilege type %s for sequence");
1001 break;
1002 case OBJECT_FUNCTION:
1003 all_privileges = ACL_ALL_RIGHTS_FUNCTION;
1004 errormsg = gettext_noop("invalid privilege type %s for function");
1005 break;
1006 case OBJECT_PROCEDURE:
1007 all_privileges = ACL_ALL_RIGHTS_FUNCTION;
1008 errormsg = gettext_noop("invalid privilege type %s for procedure");
1009 break;
1010 case OBJECT_ROUTINE:
1011 all_privileges = ACL_ALL_RIGHTS_FUNCTION;
1012 errormsg = gettext_noop("invalid privilege type %s for routine");
1013 break;
1014 case OBJECT_TYPE:
1015 all_privileges = ACL_ALL_RIGHTS_TYPE;
1016 errormsg = gettext_noop("invalid privilege type %s for type");
1017 break;
1018 case OBJECT_SCHEMA:
1019 all_privileges = ACL_ALL_RIGHTS_SCHEMA;
1020 errormsg = gettext_noop("invalid privilege type %s for schema");
1021 break;
1022 case OBJECT_LARGEOBJECT:
1023 all_privileges = ACL_ALL_RIGHTS_LARGEOBJECT;
1024 errormsg = gettext_noop("invalid privilege type %s for large object");
1025 break;
1026 default:
1027 elog(ERROR, "unrecognized GrantStmt.objtype: %d",
1028 (int) action->objtype);
1029 /* keep compiler quiet */
1030 all_privileges = ACL_NO_RIGHTS;
1031 errormsg = NULL;
1032 }
1033
1034 if (action->privileges == NIL)
1035 {
1036 iacls.all_privs = true;
1037
1038 /*
1039 * will be turned into ACL_ALL_RIGHTS_* by the internal routines
1040 * depending on the object type
1041 */
1042 iacls.privileges = ACL_NO_RIGHTS;
1043 }
1044 else
1045 {
1046 iacls.all_privs = false;
1047 iacls.privileges = ACL_NO_RIGHTS;
1048
1049 foreach(cell, action->privileges)
1050 {
1051 AccessPriv *privnode = (AccessPriv *) lfirst(cell);
1052 AclMode priv;
1053
1054 if (privnode->cols)
1055 ereport(ERROR,
1056 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1057 errmsg("default privileges cannot be set for columns")));
1058
1059 if (privnode->priv_name == NULL) /* parser mistake? */
1060 elog(ERROR, "AccessPriv node must specify privilege");
1061 priv = string_to_privilege(privnode->priv_name);
1062
1063 if (priv & ~((AclMode) all_privileges))
1064 ereport(ERROR,
1065 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1066 errmsg(errormsg, privilege_to_string(priv))));
1067
1068 iacls.privileges |= priv;
1069 }
1070 }
1071
1072 if (rolespecs == NIL)
1073 {
1074 /* Set permissions for myself */
1075 iacls.roleid = GetUserId();
1076
1077 SetDefaultACLsInSchemas(&iacls, nspnames);
1078 }
1079 else
1080 {
1081 /* Look up the role OIDs and do permissions checks */
1082 ListCell *rolecell;
1083
1084 foreach(rolecell, rolespecs)
1085 {
1086 RoleSpec *rolespec = lfirst(rolecell);
1087
1088 iacls.roleid = get_rolespec_oid(rolespec, false);
1089
1090 if (!has_privs_of_role(GetUserId(), iacls.roleid))
1091 ereport(ERROR,
1092 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1093 errmsg("permission denied to change default privileges")));
1094
1095 SetDefaultACLsInSchemas(&iacls, nspnames);
1096 }
1097 }
1098 }
1099
1100 /*
1101 * Process ALTER DEFAULT PRIVILEGES for a list of target schemas
1102 *
1103 * All fields of *iacls except nspid were filled already
1104 */
1105 static void
1106 SetDefaultACLsInSchemas(InternalDefaultACL *iacls, List *nspnames)
1107 {
1108 if (nspnames == NIL)
1109 {
1110 /* Set database-wide permissions if no schema was specified */
1111 iacls->nspid = InvalidOid;
1112
1113 SetDefaultACL(iacls);
1114 }
1115 else
1116 {
1117 /* Look up the schema OIDs and set permissions for each one */
1118 ListCell *nspcell;
1119
1120 foreach(nspcell, nspnames)
1121 {
1122 char *nspname = strVal(lfirst(nspcell));
1123
1124 iacls->nspid = get_namespace_oid(nspname, false);
1125
1126 /*
1127 * We used to insist that the target role have CREATE privileges
1128 * on the schema, since without that it wouldn't be able to create
1129 * an object for which these default privileges would apply.
1130 * However, this check proved to be more confusing than helpful,
1131 * and it also caused certain database states to not be
1132 * dumpable/restorable, since revoking CREATE doesn't cause
1133 * default privileges for the schema to go away. So now, we just
1134 * allow the ALTER; if the user lacks CREATE he'll find out when
1135 * he tries to create an object.
1136 */
1137
1138 SetDefaultACL(iacls);
1139 }
1140 }
1141 }
1142
1143
1144 /*
1145 * Create or update a pg_default_acl entry
1146 */
1147 static void
1148 SetDefaultACL(InternalDefaultACL *iacls)
1149 {
1150 AclMode this_privileges = iacls->privileges;
1151 char objtype;
1152 Relation rel;
1153 HeapTuple tuple;
1154 bool isNew;
1155 Acl *def_acl;
1156 Acl *old_acl;
1157 Acl *new_acl;
1158 HeapTuple newtuple;
1159 int noldmembers;
1160 int nnewmembers;
1161 Oid *oldmembers;
1162 Oid *newmembers;
1163
1164 rel = table_open(DefaultAclRelationId, RowExclusiveLock);
1165
1166 /*
1167 * The default for a global entry is the hard-wired default ACL for the
1168 * particular object type. The default for non-global entries is an empty
1169 * ACL. This must be so because global entries replace the hard-wired
1170 * defaults, while others are added on.
1171 */
1172 if (!OidIsValid(iacls->nspid))
1173 def_acl = acldefault(iacls->objtype, iacls->roleid);
1174 else
1175 def_acl = make_empty_acl();
1176
1177 /*
1178 * Convert ACL object type to pg_default_acl object type and handle
1179 * all_privs option
1180 */
1181 switch (iacls->objtype)
1182 {
1183 case OBJECT_TABLE:
1184 objtype = DEFACLOBJ_RELATION;
1185 if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
1186 this_privileges = ACL_ALL_RIGHTS_RELATION;
1187 break;
1188
1189 case OBJECT_SEQUENCE:
1190 objtype = DEFACLOBJ_SEQUENCE;
1191 if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
1192 this_privileges = ACL_ALL_RIGHTS_SEQUENCE;
1193 break;
1194
1195 case OBJECT_FUNCTION:
1196 objtype = DEFACLOBJ_FUNCTION;
1197 if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
1198 this_privileges = ACL_ALL_RIGHTS_FUNCTION;
1199 break;
1200
1201 case OBJECT_TYPE:
1202 objtype = DEFACLOBJ_TYPE;
1203 if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
1204 this_privileges = ACL_ALL_RIGHTS_TYPE;
1205 break;
1206
1207 case OBJECT_SCHEMA:
1208 if (OidIsValid(iacls->nspid))
1209 ereport(ERROR,
1210 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1211 errmsg("cannot use IN SCHEMA clause when using %s",
1212 "GRANT/REVOKE ON SCHEMAS")));
1213 objtype = DEFACLOBJ_NAMESPACE;
1214 if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
1215 this_privileges = ACL_ALL_RIGHTS_SCHEMA;
1216 break;
1217
1218 case OBJECT_LARGEOBJECT:
1219 if (OidIsValid(iacls->nspid))
1220 ereport(ERROR,
1221 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1222 errmsg("cannot use IN SCHEMA clause when using %s",
1223 "GRANT/REVOKE ON LARGE OBJECTS")));
1224 objtype = DEFACLOBJ_LARGEOBJECT;
1225 if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
1226 this_privileges = ACL_ALL_RIGHTS_LARGEOBJECT;
1227 break;
1228
1229 default:
1230 elog(ERROR, "unrecognized object type: %d",
1231 (int) iacls->objtype);
1232 objtype = 0; /* keep compiler quiet */
1233 break;
1234 }
1235
1236 /* Search for existing row for this object type in catalog */
1237 tuple = SearchSysCache3(DEFACLROLENSPOBJ,
1238 ObjectIdGetDatum(iacls->roleid),
1239 ObjectIdGetDatum(iacls->nspid),
1240 CharGetDatum(objtype));
1241
1242 if (HeapTupleIsValid(tuple))
1243 {
1244 Datum aclDatum;
1245 bool isNull;
1246
1247 aclDatum = SysCacheGetAttr(DEFACLROLENSPOBJ, tuple,
1248 Anum_pg_default_acl_defaclacl,
1249 &isNull);
1250 if (!isNull)
1251 old_acl = DatumGetAclPCopy(aclDatum);
1252 else
1253 old_acl = NULL; /* this case shouldn't happen, probably */
1254 isNew = false;
1255 }
1256 else
1257 {
1258 old_acl = NULL;
1259 isNew = true;
1260 }
1261
1262 if (old_acl != NULL)
1263 {
1264 /*
1265 * We need the members of both old and new ACLs so we can correct the
1266 * shared dependency information. Collect data before
1267 * merge_acl_with_grant throws away old_acl.
1268 */
1269 noldmembers = aclmembers(old_acl, &oldmembers);
1270 }
1271 else
1272 {
1273 /* If no or null entry, start with the default ACL value */
1274 old_acl = aclcopy(def_acl);
1275 /* There are no old member roles according to the catalogs */
1276 noldmembers = 0;
1277 oldmembers = NULL;
1278 }
1279
1280 /*
1281 * Generate new ACL. Grantor of rights is always the same as the target
1282 * role.
1283 */
1284 new_acl = merge_acl_with_grant(old_acl,
1285 iacls->is_grant,
1286 iacls->grant_option,
1287 iacls->behavior,
1288 iacls->grantees,
1289 this_privileges,
1290 iacls->roleid,
1291 iacls->roleid);
1292
1293 /*
1294 * If the result is the same as the default value, we do not need an
1295 * explicit pg_default_acl entry, and should in fact remove the entry if
1296 * it exists. Must sort both arrays to compare properly.
1297 */
1298 aclitemsort(new_acl);
1299 aclitemsort(def_acl);
1300 if (aclequal(new_acl, def_acl))
1301 {
1302 /* delete old entry, if indeed there is one */
1303 if (!isNew)
1304 {
1305 ObjectAddress myself;
1306
1307 /*
1308 * The dependency machinery will take care of removing all
1309 * associated dependency entries. We use DROP_RESTRICT since
1310 * there shouldn't be anything depending on this entry.
1311 */
1312 myself.classId = DefaultAclRelationId;
1313 myself.objectId = ((Form_pg_default_acl) GETSTRUCT(tuple))->oid;
1314 myself.objectSubId = 0;
1315
1316 performDeletion(&myself, DROP_RESTRICT, 0);
1317 }
1318 }
1319 else
1320 {
1321 Datum values[Natts_pg_default_acl] = {0};
1322 bool nulls[Natts_pg_default_acl] = {0};
1323 bool replaces[Natts_pg_default_acl] = {0};
1324 Oid defAclOid;
1325
1326 if (isNew)
1327 {
1328 /* insert new entry */
1329 defAclOid = GetNewOidWithIndex(rel, DefaultAclOidIndexId,
1330 Anum_pg_default_acl_oid);
1331 values[Anum_pg_default_acl_oid - 1] = ObjectIdGetDatum(defAclOid);
1332 values[Anum_pg_default_acl_defaclrole - 1] = ObjectIdGetDatum(iacls->roleid);
1333 values[Anum_pg_default_acl_defaclnamespace - 1] = ObjectIdGetDatum(iacls->nspid);
1334 values[Anum_pg_default_acl_defaclobjtype - 1] = CharGetDatum(objtype);
1335 values[Anum_pg_default_acl_defaclacl - 1] = PointerGetDatum(new_acl);
1336
1337 newtuple = heap_form_tuple(RelationGetDescr(rel), values, nulls);
1338 CatalogTupleInsert(rel, newtuple);
1339 }
1340 else
1341 {
1342 defAclOid = ((Form_pg_default_acl) GETSTRUCT(tuple))->oid;
1343
1344 /* update existing entry */
1345 values[Anum_pg_default_acl_defaclacl - 1] = PointerGetDatum(new_acl);
1346 replaces[Anum_pg_default_acl_defaclacl - 1] = true;
1347
1348 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
1349 values, nulls, replaces);
1350 CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1351 }
1352
1353 /* these dependencies don't change in an update */
1354 if (isNew)
1355 {
1356 /* dependency on role */
1357 recordDependencyOnOwner(DefaultAclRelationId, defAclOid,
1358 iacls->roleid);
1359
1360 /* dependency on namespace */
1361 if (OidIsValid(iacls->nspid))
1362 {
1363 ObjectAddress myself,
1364 referenced;
1365
1366 myself.classId = DefaultAclRelationId;
1367 myself.objectId = defAclOid;
1368 myself.objectSubId = 0;
1369
1370 referenced.classId = NamespaceRelationId;
1371 referenced.objectId = iacls->nspid;
1372 referenced.objectSubId = 0;
1373
1374 recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
1375 }
1376 }
1377
1378 /*
1379 * Update the shared dependency ACL info
1380 */
1381 nnewmembers = aclmembers(new_acl, &newmembers);
1382
1383 updateAclDependencies(DefaultAclRelationId,
1384 defAclOid, 0,
1385 iacls->roleid,
1386 noldmembers, oldmembers,
1387 nnewmembers, newmembers);
1388
1389 if (isNew)
1390 InvokeObjectPostCreateHook(DefaultAclRelationId, defAclOid, 0);
1391 else
1392 InvokeObjectPostAlterHook(DefaultAclRelationId, defAclOid, 0);
1393 }
1394
1395 if (HeapTupleIsValid(tuple))
1396 ReleaseSysCache(tuple);
1397
1398 table_close(rel, RowExclusiveLock);
1399
1400 /* prevent error when processing duplicate objects */
1401 CommandCounterIncrement();
1402 }
1403
1404
1405 /*
1406 * RemoveRoleFromObjectACL
1407 *
1408 * Used by shdepDropOwned to remove mentions of a role in ACLs.
1409 *
1410 * Notice that this doesn't accept an objsubid parameter, which is a bit bogus
1411 * since the pg_shdepend record that caused us to call it certainly had one.
1412 * If, for example, pg_shdepend records the existence of a permission on
1413 * mytable.mycol, this function will effectively issue a REVOKE ALL ON TABLE
1414 * mytable. That gets the job done because (per SQL spec) such a REVOKE also
1415 * revokes per-column permissions. We could not recreate a situation where
1416 * the role has table-level but not column-level permissions; but it's okay
1417 * (for now anyway) because this is only used when we're dropping the role
1418 * and so all its permissions everywhere must go away. At worst it's a bit
1419 * inefficient if the role has column permissions on several columns of the
1420 * same table.
1421 */
1422 void
1423 RemoveRoleFromObjectACL(Oid roleid, Oid classid, Oid objid)
1424 {
1425 if (classid == DefaultAclRelationId)
1426 {
1427 InternalDefaultACL iacls;
1428 Form_pg_default_acl pg_default_acl_tuple;
1429 Relation rel;
1430 ScanKeyData skey[1];
1431 SysScanDesc scan;
1432 HeapTuple tuple;
1433
1434 /* first fetch info needed by SetDefaultACL */
1435 rel = table_open(DefaultAclRelationId, AccessShareLock);
1436
1437 ScanKeyInit(&skey[0],
1438 Anum_pg_default_acl_oid,
1439 BTEqualStrategyNumber, F_OIDEQ,
1440 ObjectIdGetDatum(objid));
1441
1442 scan = systable_beginscan(rel, DefaultAclOidIndexId, true,
1443 NULL, 1, skey);
1444
1445 tuple = systable_getnext(scan);
1446
1447 if (!HeapTupleIsValid(tuple))
1448 elog(ERROR, "could not find tuple for default ACL %u", objid);
1449
1450 pg_default_acl_tuple = (Form_pg_default_acl) GETSTRUCT(tuple);
1451
1452 iacls.roleid = pg_default_acl_tuple->defaclrole;
1453 iacls.nspid = pg_default_acl_tuple->defaclnamespace;
1454
1455 switch (pg_default_acl_tuple->defaclobjtype)
1456 {
1457 case DEFACLOBJ_RELATION:
1458 iacls.objtype = OBJECT_TABLE;
1459 break;
1460 case DEFACLOBJ_SEQUENCE:
1461 iacls.objtype = OBJECT_SEQUENCE;
1462 break;
1463 case DEFACLOBJ_FUNCTION:
1464 iacls.objtype = OBJECT_FUNCTION;
1465 break;
1466 case DEFACLOBJ_TYPE:
1467 iacls.objtype = OBJECT_TYPE;
1468 break;
1469 case DEFACLOBJ_NAMESPACE:
1470 iacls.objtype = OBJECT_SCHEMA;
1471 break;
1472 case DEFACLOBJ_LARGEOBJECT:
1473 iacls.objtype = OBJECT_LARGEOBJECT;
1474 break;
1475 default:
1476 /* Shouldn't get here */
1477 elog(ERROR, "unexpected default ACL type: %d",
1478 (int) pg_default_acl_tuple->defaclobjtype);
1479 break;
1480 }
1481
1482 systable_endscan(scan);
1483 table_close(rel, AccessShareLock);
1484
1485 iacls.is_grant = false;
1486 iacls.all_privs = true;
1487 iacls.privileges = ACL_NO_RIGHTS;
1488 iacls.grantees = list_make1_oid(roleid);
1489 iacls.grant_option = false;
1490 iacls.behavior = DROP_CASCADE;
1491
1492 /* Do it */
1493 SetDefaultACL(&iacls);
1494 }
1495 else
1496 {
1497 InternalGrant istmt;
1498
1499 switch (classid)
1500 {
1501 case RelationRelationId:
1502 /* it's OK to use TABLE for a sequence */
1503 istmt.objtype = OBJECT_TABLE;
1504 break;
1505 case DatabaseRelationId:
1506 istmt.objtype = OBJECT_DATABASE;
1507 break;
1508 case TypeRelationId:
1509 istmt.objtype = OBJECT_TYPE;
1510 break;
1511 case ProcedureRelationId:
1512 istmt.objtype = OBJECT_ROUTINE;
1513 break;
1514 case LanguageRelationId:
1515 istmt.objtype = OBJECT_LANGUAGE;
1516 break;
1517 case LargeObjectRelationId:
1518 istmt.objtype = OBJECT_LARGEOBJECT;
1519 break;
1520 case NamespaceRelationId:
1521 istmt.objtype = OBJECT_SCHEMA;
1522 break;
1523 case TableSpaceRelationId:
1524 istmt.objtype = OBJECT_TABLESPACE;
1525 break;
1526 case ForeignServerRelationId:
1527 istmt.objtype = OBJECT_FOREIGN_SERVER;
1528 break;
1529 case ForeignDataWrapperRelationId:
1530 istmt.objtype = OBJECT_FDW;
1531 break;
1532 case ParameterAclRelationId:
1533 istmt.objtype = OBJECT_PARAMETER_ACL;
1534 break;
1535 default:
1536 elog(ERROR, "unexpected object class %u", classid);
1537 break;
1538 }
1539 istmt.is_grant = false;
1540 istmt.objects = list_make1_oid(objid);
1541 istmt.all_privs = true;
1542 istmt.privileges = ACL_NO_RIGHTS;
1543 istmt.col_privs = NIL;
1544 istmt.grantees = list_make1_oid(roleid);
1545 istmt.grant_option = false;
1546 istmt.behavior = DROP_CASCADE;
1547
1548 ExecGrantStmt_oids(&istmt);
1549 }
1550 }
1551
1552
1553 /*
1554 * expand_col_privileges
1555 *
1556 * OR the specified privilege(s) into per-column array entries for each
1557 * specified attribute. The per-column array is indexed starting at
1558 * FirstLowInvalidHeapAttributeNumber, up to relation's last attribute.
1559 */
1560 static void
1561 expand_col_privileges(List *colnames, Oid table_oid,
1562 AclMode this_privileges,
1563 AclMode *col_privileges,
1564 int num_col_privileges)
1565 {
1566 ListCell *cell;
1567
1568 foreach(cell, colnames)
1569 {
1570 char *colname = strVal(lfirst(cell));
1571 AttrNumber attnum;
1572
1573 attnum = get_attnum(table_oid, colname);
1574 if (attnum == InvalidAttrNumber)
1575 ereport(ERROR,
1576 (errcode(ERRCODE_UNDEFINED_COLUMN),
1577 errmsg("column \"%s\" of relation \"%s\" does not exist",
1578 colname, get_rel_name(table_oid))));
1579 attnum -= FirstLowInvalidHeapAttributeNumber;
1580 if (attnum <= 0 || attnum >= num_col_privileges)
1581 elog(ERROR, "column number out of range"); /* safety check */
1582 col_privileges[attnum] |= this_privileges;
1583 }
1584 }
1585
1586 /*
1587 * expand_all_col_privileges
1588 *
1589 * OR the specified privilege(s) into per-column array entries for each valid
1590 * attribute of a relation. The per-column array is indexed starting at
1591 * FirstLowInvalidHeapAttributeNumber, up to relation's last attribute.
1592 */
1593 static void
1594 expand_all_col_privileges(Oid table_oid, Form_pg_class classForm,
1595 AclMode this_privileges,
1596 AclMode *col_privileges,
1597 int num_col_privileges)
1598 {
1599 AttrNumber curr_att;
1600
1601 Assert(classForm->relnatts - FirstLowInvalidHeapAttributeNumber < num_col_privileges);
1602 for (curr_att = FirstLowInvalidHeapAttributeNumber + 1;
1603 curr_att <= classForm->relnatts;
1604 curr_att++)
1605 {
1606 HeapTuple attTuple;
1607 bool isdropped;
1608
1609 if (curr_att == InvalidAttrNumber)
1610 continue;
1611
1612 /* Views don't have any system columns at all */
1613 if (classForm->relkind == RELKIND_VIEW && curr_att < 0)
1614 continue;
1615
1616 attTuple = SearchSysCache2(ATTNUM,
1617 ObjectIdGetDatum(table_oid),
1618 Int16GetDatum(curr_att));
1619 if (!HeapTupleIsValid(attTuple))
1620 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1621 curr_att, table_oid);
1622
1623 isdropped = ((Form_pg_attribute) GETSTRUCT(attTuple))->attisdropped;
1624
1625 ReleaseSysCache(attTuple);
1626
1627 /* ignore dropped columns */
1628 if (isdropped)
1629 continue;
1630
1631 col_privileges[curr_att - FirstLowInvalidHeapAttributeNumber] |= this_privileges;
1632 }
1633 }
1634
1635 /*
1636 * This processes attributes, but expects to be called from
1637 * ExecGrant_Relation, not directly from ExecuteGrantStmt.
1638 */
1639 static void
1640 ExecGrant_Attribute(InternalGrant *istmt, Oid relOid, const char *relname,
1641 AttrNumber attnum, Oid ownerId, AclMode col_privileges,
1642 Relation attRelation, const Acl *old_rel_acl)
1643 {
1644 HeapTuple attr_tuple;
1645 Form_pg_attribute pg_attribute_tuple;
1646 Acl *old_acl;
1647 Acl *new_acl;
1648 Acl *merged_acl;
1649 Datum aclDatum;
1650 bool isNull;
1651 Oid grantorId;
1652 AclMode avail_goptions;
1653 bool need_update;
1654 HeapTuple newtuple;
1655 Datum values[Natts_pg_attribute] = {0};
1656 bool nulls[Natts_pg_attribute] = {0};
1657 bool replaces[Natts_pg_attribute] = {0};
1658 int noldmembers;
1659 int nnewmembers;
1660 Oid *oldmembers;
1661 Oid *newmembers;
1662
1663 attr_tuple = SearchSysCache2(ATTNUM,
1664 ObjectIdGetDatum(relOid),
1665 Int16GetDatum(attnum));
1666 if (!HeapTupleIsValid(attr_tuple))
1667 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1668 attnum, relOid);
1669 pg_attribute_tuple = (Form_pg_attribute) GETSTRUCT(attr_tuple);
1670
1671 /*
1672 * Get working copy of existing ACL. If there's no ACL, substitute the
1673 * proper default.
1674 */
1675 aclDatum = SysCacheGetAttr(ATTNUM, attr_tuple, Anum_pg_attribute_attacl,
1676 &isNull);
1677 if (isNull)
1678 {
1679 old_acl = acldefault(OBJECT_COLUMN, ownerId);
1680 /* There are no old member roles according to the catalogs */
1681 noldmembers = 0;
1682 oldmembers = NULL;
1683 }
1684 else
1685 {
1686 old_acl = DatumGetAclPCopy(aclDatum);
1687 /* Get the roles mentioned in the existing ACL */
1688 noldmembers = aclmembers(old_acl, &oldmembers);
1689 }
1690
1691 /*
1692 * In select_best_grantor we should consider existing table-level ACL bits
1693 * as well as the per-column ACL. Build a new ACL that is their
1694 * concatenation. (This is a bit cheap and dirty compared to merging them
1695 * properly with no duplications, but it's all we need here.)
1696 */
1697 merged_acl = aclconcat(old_rel_acl, old_acl);
1698
1699 /* Determine ID to do the grant as, and available grant options */
1700 select_best_grantor(GetUserId(), col_privileges,
1701 merged_acl, ownerId,
1702 &grantorId, &avail_goptions);
1703
1704 pfree(merged_acl);
1705
1706 /*
1707 * Restrict the privileges to what we can actually grant, and emit the
1708 * standards-mandated warning and error messages. Note: we don't track
1709 * whether the user actually used the ALL PRIVILEGES(columns) syntax for
1710 * each column; we just approximate it by whether all the possible
1711 * privileges are specified now. Since the all_privs flag only determines
1712 * whether a warning is issued, this seems close enough.
1713 */
1714 col_privileges =
1715 restrict_and_check_grant(istmt->is_grant, avail_goptions,
1716 (col_privileges == ACL_ALL_RIGHTS_COLUMN),
1717 col_privileges,
1718 relOid, grantorId, OBJECT_COLUMN,
1719 relname, attnum,
1720 NameStr(pg_attribute_tuple->attname));
1721
1722 /*
1723 * Generate new ACL.
1724 */
1725 new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
1726 istmt->grant_option,
1727 istmt->behavior, istmt->grantees,
1728 col_privileges, grantorId,
1729 ownerId);
1730
1731 /*
1732 * We need the members of both old and new ACLs so we can correct the
1733 * shared dependency information.
1734 */
1735 nnewmembers = aclmembers(new_acl, &newmembers);
1736
1737 /* finished building new ACL value, now insert it */
1738
1739 /*
1740 * If the updated ACL is empty, we can set attacl to null, and maybe even
1741 * avoid an update of the pg_attribute row. This is worth testing because
1742 * we'll come through here multiple times for any relation-level REVOKE,
1743 * even if there were never any column GRANTs. Note we are assuming that
1744 * the "default" ACL state for columns is empty.
1745 */
1746 if (ACL_NUM(new_acl) > 0)
1747 {
1748 values[Anum_pg_attribute_attacl - 1] = PointerGetDatum(new_acl);
1749 need_update = true;
1750 }
1751 else
1752 {
1753 nulls[Anum_pg_attribute_attacl - 1] = true;
1754 need_update = !isNull;
1755 }
1756 replaces[Anum_pg_attribute_attacl - 1] = true;
1757
1758 if (need_update)
1759 {
1760 newtuple = heap_modify_tuple(attr_tuple, RelationGetDescr(attRelation),
1761 values, nulls, replaces);
1762
1763 CatalogTupleUpdate(attRelation, &newtuple->t_self, newtuple);
1764
1765 /* Update initial privileges for extensions */
1766 recordExtensionInitPriv(relOid, RelationRelationId, attnum,
1767 ACL_NUM(new_acl) > 0 ? new_acl : NULL);
1768
1769 /* Update the shared dependency ACL info */
1770 updateAclDependencies(RelationRelationId, relOid, attnum,
1771 ownerId,
1772 noldmembers, oldmembers,
1773 nnewmembers, newmembers);
1774 }
1775
1776 pfree(new_acl);
1777
1778 ReleaseSysCache(attr_tuple);
1779 }
1780
1781 /*
1782 * This processes both sequences and non-sequences.
1783 */
1784 static void
1785 ExecGrant_Relation(InternalGrant *istmt)
1786 {
1787 Relation relation;
1788 Relation attRelation;
1789 ListCell *cell;
1790
1791 relation = table_open(RelationRelationId, RowExclusiveLock);
1792 attRelation = table_open(AttributeRelationId, RowExclusiveLock);
1793
1794 foreach(cell, istmt->objects)
1795 {
1796 Oid relOid = lfirst_oid(cell);
1797 Datum aclDatum;
1798 Form_pg_class pg_class_tuple;
1799 bool isNull;
1800 AclMode this_privileges;
1801 AclMode *col_privileges;
1802 int num_col_privileges;
1803 bool have_col_privileges;
1804 Acl *old_acl;
1805 Acl *old_rel_acl;
1806 int noldmembers;
1807 Oid *oldmembers;
1808 Oid ownerId;
1809 HeapTuple tuple;
1810 ListCell *cell_colprivs;
1811
1812 tuple = SearchSysCacheLocked1(RELOID, ObjectIdGetDatum(relOid));
1813 if (!HeapTupleIsValid(tuple))
1814 elog(ERROR, "cache lookup failed for relation %u", relOid);
1815 pg_class_tuple = (Form_pg_class) GETSTRUCT(tuple);
1816
1817 /* Not sensible to grant on an index */
1818 if (pg_class_tuple->relkind == RELKIND_INDEX ||
1819 pg_class_tuple->relkind == RELKIND_PARTITIONED_INDEX)
1820 ereport(ERROR,
1821 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1822 errmsg("\"%s\" is an index",
1823 NameStr(pg_class_tuple->relname))));
1824
1825 /* Composite types aren't tables either */
1826 if (pg_class_tuple->relkind == RELKIND_COMPOSITE_TYPE)
1827 ereport(ERROR,
1828 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1829 errmsg("\"%s\" is a composite type",
1830 NameStr(pg_class_tuple->relname))));
1831
1832 /* Used GRANT SEQUENCE on a non-sequence? */
1833 if (istmt->objtype == OBJECT_SEQUENCE &&
1834 pg_class_tuple->relkind != RELKIND_SEQUENCE)
1835 ereport(ERROR,
1836 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1837 errmsg("\"%s\" is not a sequence",
1838 NameStr(pg_class_tuple->relname))));
1839
1840 /* Adjust the default permissions based on object type */
1841 if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
1842 {
1843 if (pg_class_tuple->relkind == RELKIND_SEQUENCE)
1844 this_privileges = ACL_ALL_RIGHTS_SEQUENCE;
1845 else
1846 this_privileges = ACL_ALL_RIGHTS_RELATION;
1847 }
1848 else
1849 this_privileges = istmt->privileges;
1850
1851 /*
1852 * The GRANT TABLE syntax can be used for sequences and non-sequences,
1853 * so we have to look at the relkind to determine the supported
1854 * permissions. The OR of table and sequence permissions were already
1855 * checked.
1856 */
1857 if (istmt->objtype == OBJECT_TABLE)
1858 {
1859 if (pg_class_tuple->relkind == RELKIND_SEQUENCE)
1860 {
1861 /*
1862 * For backward compatibility, just throw a warning for
1863 * invalid sequence permissions when using the non-sequence
1864 * GRANT syntax.
1865 */
1866 if (this_privileges & ~((AclMode) ACL_ALL_RIGHTS_SEQUENCE))
1867 {
1868 /*
1869 * Mention the object name because the user needs to know
1870 * which operations succeeded. This is required because
1871 * WARNING allows the command to continue.
1872 */
1873 ereport(WARNING,
1874 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1875 errmsg("sequence \"%s\" only supports USAGE, SELECT, and UPDATE privileges",
1876 NameStr(pg_class_tuple->relname))));
1877 this_privileges &= (AclMode) ACL_ALL_RIGHTS_SEQUENCE;
1878 }
1879 }
1880 else
1881 {
1882 if (this_privileges & ~((AclMode) ACL_ALL_RIGHTS_RELATION))
1883 {
1884 /*
1885 * USAGE is the only permission supported by sequences but
1886 * not by non-sequences. Don't mention the object name
1887 * because we didn't in the combined TABLE | SEQUENCE
1888 * check.
1889 */
1890 ereport(ERROR,
1891 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1892 errmsg("invalid privilege type %s for table",
1893 "USAGE")));
1894 }
1895 }
1896 }
1897
1898 /*
1899 * Set up array in which we'll accumulate any column privilege bits
1900 * that need modification. The array is indexed such that entry [0]
1901 * corresponds to FirstLowInvalidHeapAttributeNumber.
1902 */
1903 num_col_privileges = pg_class_tuple->relnatts - FirstLowInvalidHeapAttributeNumber + 1;
1904 col_privileges = (AclMode *) palloc0(num_col_privileges * sizeof(AclMode));
1905 have_col_privileges = false;
1906
1907 /*
1908 * If we are revoking relation privileges that are also column
1909 * privileges, we must implicitly revoke them from each column too,
1910 * per SQL spec. (We don't need to implicitly add column privileges
1911 * during GRANT because the permissions-checking code always checks
1912 * both relation and per-column privileges.)
1913 */
1914 if (!istmt->is_grant &&
1915 (this_privileges & ACL_ALL_RIGHTS_COLUMN) != 0)
1916 {
1917 expand_all_col_privileges(relOid, pg_class_tuple,
1918 this_privileges & ACL_ALL_RIGHTS_COLUMN,
1919 col_privileges,
1920 num_col_privileges);
1921 have_col_privileges = true;
1922 }
1923
1924 /*
1925 * Get owner ID and working copy of existing ACL. If there's no ACL,
1926 * substitute the proper default.
1927 */
1928 ownerId = pg_class_tuple->relowner;
1929 aclDatum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relacl,
1930 &isNull);
1931 if (isNull)
1932 {
1933 switch (pg_class_tuple->relkind)
1934 {
1935 case RELKIND_SEQUENCE:
1936 old_acl = acldefault(OBJECT_SEQUENCE, ownerId);
1937 break;
1938 default:
1939 old_acl = acldefault(OBJECT_TABLE, ownerId);
1940 break;
1941 }
1942 /* There are no old member roles according to the catalogs */
1943 noldmembers = 0;
1944 oldmembers = NULL;
1945 }
1946 else
1947 {
1948 old_acl = DatumGetAclPCopy(aclDatum);
1949 /* Get the roles mentioned in the existing ACL */
1950 noldmembers = aclmembers(old_acl, &oldmembers);
1951 }
1952
1953 /* Need an extra copy of original rel ACL for column handling */
1954 old_rel_acl = aclcopy(old_acl);
1955
1956 /*
1957 * Handle relation-level privileges, if any were specified
1958 */
1959 if (this_privileges != ACL_NO_RIGHTS)
1960 {
1961 AclMode avail_goptions;
1962 Acl *new_acl;
1963 Oid grantorId;
1964 HeapTuple newtuple;
1965 Datum values[Natts_pg_class] = {0};
1966 bool nulls[Natts_pg_class] = {0};
1967 bool replaces[Natts_pg_class] = {0};
1968 int nnewmembers;
1969 Oid *newmembers;
1970 ObjectType objtype;
1971
1972 /* Determine ID to do the grant as, and available grant options */
1973 select_best_grantor(GetUserId(), this_privileges,
1974 old_acl, ownerId,
1975 &grantorId, &avail_goptions);
1976
1977 switch (pg_class_tuple->relkind)
1978 {
1979 case RELKIND_SEQUENCE:
1980 objtype = OBJECT_SEQUENCE;
1981 break;
1982 default:
1983 objtype = OBJECT_TABLE;
1984 break;
1985 }
1986
1987 /*
1988 * Restrict the privileges to what we can actually grant, and emit
1989 * the standards-mandated warning and error messages.
1990 */
1991 this_privileges =
1992 restrict_and_check_grant(istmt->is_grant, avail_goptions,
1993 istmt->all_privs, this_privileges,
1994 relOid, grantorId, objtype,
1995 NameStr(pg_class_tuple->relname),
1996 0, NULL);
1997
1998 /*
1999 * Generate new ACL.
2000 */
2001 new_acl = merge_acl_with_grant(old_acl,
2002 istmt->is_grant,
2003 istmt->grant_option,
2004 istmt->behavior,
2005 istmt->grantees,
2006 this_privileges,
2007 grantorId,
2008 ownerId);
2009
2010 /*
2011 * We need the members of both old and new ACLs so we can correct
2012 * the shared dependency information.
2013 */
2014 nnewmembers = aclmembers(new_acl, &newmembers);
2015
2016 /* finished building new ACL value, now insert it */
2017 replaces[Anum_pg_class_relacl - 1] = true;
2018 values[Anum_pg_class_relacl - 1] = PointerGetDatum(new_acl);
2019
2020 newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation),
2021 values, nulls, replaces);
2022
2023 CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
2024 UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
2025
2026 /* Update initial privileges for extensions */
2027 recordExtensionInitPriv(relOid, RelationRelationId, 0, new_acl);
2028
2029 /* Update the shared dependency ACL info */
2030 updateAclDependencies(RelationRelationId, relOid, 0,
2031 ownerId,
2032 noldmembers, oldmembers,
2033 nnewmembers, newmembers);
2034
2035 pfree(new_acl);
2036 }
2037 else
2038 UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
2039
2040 /*
2041 * Handle column-level privileges, if any were specified or implied.
2042 * We first expand the user-specified column privileges into the
2043 * array, and then iterate over all nonempty array entries.
2044 */
2045 foreach(cell_colprivs, istmt->col_privs)
2046 {
2047 AccessPriv *col_privs = (AccessPriv *) lfirst(cell_colprivs);
2048
2049 if (col_privs->priv_name == NULL)
2050 this_privileges = ACL_ALL_RIGHTS_COLUMN;
2051 else
2052 this_privileges = string_to_privilege(col_privs->priv_name);
2053
2054 if (this_privileges & ~((AclMode) ACL_ALL_RIGHTS_COLUMN))
2055 ereport(ERROR,
2056 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
2057 errmsg("invalid privilege type %s for column",
2058 privilege_to_string(this_privileges))));
2059
2060 if (pg_class_tuple->relkind == RELKIND_SEQUENCE &&
2061 this_privileges & ~((AclMode) ACL_SELECT))
2062 {
2063 /*
2064 * The only column privilege allowed on sequences is SELECT.
2065 * This is a warning not error because we do it that way for
2066 * relation-level privileges.
2067 */
2068 ereport(WARNING,
2069 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
2070 errmsg("sequence \"%s\" only supports SELECT column privileges",
2071 NameStr(pg_class_tuple->relname))));
2072
2073 this_privileges &= (AclMode) ACL_SELECT;
2074 }
2075
2076 expand_col_privileges(col_privs->cols, relOid,
2077 this_privileges,
2078 col_privileges,
2079 num_col_privileges);
2080 have_col_privileges = true;
2081 }
2082
2083 if (have_col_privileges)
2084 {
2085 AttrNumber i;
2086
2087 for (i = 0; i < num_col_privileges; i++)
2088 {
2089 if (col_privileges[i] == ACL_NO_RIGHTS)
2090 continue;
2091 ExecGrant_Attribute(istmt,
2092 relOid,
2093 NameStr(pg_class_tuple->relname),
2094 i + FirstLowInvalidHeapAttributeNumber,
2095 ownerId,
2096 col_privileges[i],
2097 attRelation,
2098 old_rel_acl);
2099 }
2100 }
2101
2102 pfree(old_rel_acl);
2103 pfree(col_privileges);
2104
2105 ReleaseSysCache(tuple);
2106
2107 /* prevent error when processing duplicate objects */
2108 CommandCounterIncrement();
2109 }
2110
2111 table_close(attRelation, RowExclusiveLock);
2112 table_close(relation, RowExclusiveLock);
2113 }
2114
2115 static void
2116 ExecGrant_common(InternalGrant *istmt, Oid classid, AclMode default_privs,
2117 void (*object_check) (InternalGrant *istmt, HeapTuple tuple))
2118 {
2119 int cacheid;
2120 Relation relation;
2121 ListCell *cell;
2122
2123 if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
2124 istmt->privileges = default_privs;
2125
2126 cacheid = get_object_catcache_oid(classid);
2127
2128 relation = table_open(classid, RowExclusiveLock);
2129
2130 foreach(cell, istmt->objects)
2131 {
2132 Oid objectid = lfirst_oid(cell);
2133 Datum aclDatum;
2134 Datum nameDatum;
2135 bool isNull;
2136 AclMode avail_goptions;
2137 AclMode this_privileges;
2138 Acl *old_acl;
2139 Acl *new_acl;
2140 Oid grantorId;
2141 Oid ownerId;
2142 HeapTuple tuple;
2143 HeapTuple newtuple;
2144 Datum *values = palloc0_array(Datum, RelationGetDescr(relation)->natts);
2145 bool *nulls = palloc0_array(bool, RelationGetDescr(relation)->natts);
2146 bool *replaces = palloc0_array(bool, RelationGetDescr(relation)->natts);
2147 int noldmembers;
2148 int nnewmembers;
2149 Oid *oldmembers;
2150 Oid *newmembers;
2151
2152 tuple = SearchSysCacheLocked1(cacheid, ObjectIdGetDatum(objectid));
2153 if (!HeapTupleIsValid(tuple))
2154 elog(ERROR, "cache lookup failed for %s %u", get_object_class_descr(classid), objectid);
2155
2156 /*
2157 * Additional object-type-specific checks
2158 */
2159 if (object_check)
2160 object_check(istmt, tuple);
2161
2162 /*
2163 * Get owner ID and working copy of existing ACL. If there's no ACL,
2164 * substitute the proper default.
2165 */
2166 ownerId = DatumGetObjectId(SysCacheGetAttrNotNull(cacheid,
2167 tuple,
2168 get_object_attnum_owner(classid)));
2169 aclDatum = SysCacheGetAttr(cacheid,
2170 tuple,
2171 get_object_attnum_acl(classid),
2172 &isNull);
2173 if (isNull)
2174 {
2175 old_acl = acldefault(get_object_type(classid, objectid), ownerId);
2176 /* There are no old member roles according to the catalogs */
2177 noldmembers = 0;
2178 oldmembers = NULL;
2179 }
2180 else
2181 {
2182 old_acl = DatumGetAclPCopy(aclDatum);
2183 /* Get the roles mentioned in the existing ACL */
2184 noldmembers = aclmembers(old_acl, &oldmembers);
2185 }
2186
2187 /* Determine ID to do the grant as, and available grant options */
2188 select_best_grantor(GetUserId(), istmt->privileges,
2189 old_acl, ownerId,
2190 &grantorId, &avail_goptions);
2191
2192 nameDatum = SysCacheGetAttrNotNull(cacheid, tuple,
2193 get_object_attnum_name(classid));
2194
2195 /*
2196 * Restrict the privileges to what we can actually grant, and emit the
2197 * standards-mandated warning and error messages.
2198 */
2199 this_privileges =
2200 restrict_and_check_grant(istmt->is_grant, avail_goptions,
2201 istmt->all_privs, istmt->privileges,
2202 objectid, grantorId, get_object_type(classid, objectid),
2203 NameStr(*DatumGetName(nameDatum)),
2204 0, NULL);
2205
2206 /*
2207 * Generate new ACL.
2208 */
2209 new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
2210 istmt->grant_option, istmt->behavior,
2211 istmt->grantees, this_privileges,
2212 grantorId, ownerId);
2213
2214 /*
2215 * We need the members of both old and new ACLs so we can correct the
2216 * shared dependency information.
2217 */
2218 nnewmembers = aclmembers(new_acl, &newmembers);
2219
2220 /* finished building new ACL value, now insert it */
2221 replaces[get_object_attnum_acl(classid) - 1] = true;
2222 values[get_object_attnum_acl(classid) - 1] = PointerGetDatum(new_acl);
2223
2224 newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
2225 nulls, replaces);
2226
2227 CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
2228 UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
2229
2230 /* Update initial privileges for extensions */
2231 recordExtensionInitPriv(objectid, classid, 0, new_acl);
2232
2233 /* Update the shared dependency ACL info */
2234 updateAclDependencies(classid,
2235 objectid, 0,
2236 ownerId,
2237 noldmembers, oldmembers,
2238 nnewmembers, newmembers);
2239
2240 ReleaseSysCache(tuple);
2241
2242 pfree(new_acl);
2243
2244 /* prevent error when processing duplicate objects */
2245 CommandCounterIncrement();
2246 }
2247
2248 table_close(relation, RowExclusiveLock);
2249 }
2250
2251 static void
2252 ExecGrant_Language_check(InternalGrant *istmt, HeapTuple tuple)
2253 {
2254 Form_pg_language pg_language_tuple;
2255
2256 pg_language_tuple = (Form_pg_language) GETSTRUCT(tuple);
2257
2258 if (!pg_language_tuple->lanpltrusted)
2259 ereport(ERROR,
2260 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2261 errmsg("language \"%s\" is not trusted",
2262 NameStr(pg_language_tuple->lanname)),
2263 errdetail("GRANT and REVOKE are not allowed on untrusted languages, "
2264 "because only superusers can use untrusted languages.")));
2265 }
2266
2267 static void
2268 ExecGrant_Largeobject(InternalGrant *istmt)
2269 {
2270 Relation relation;
2271 ListCell *cell;
2272
2273 if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
2274 istmt->privileges = ACL_ALL_RIGHTS_LARGEOBJECT;
2275
2276 relation = table_open(LargeObjectMetadataRelationId,
2277 RowExclusiveLock);
2278
2279 foreach(cell, istmt->objects)
2280 {
2281 Oid loid = lfirst_oid(cell);
2282 Form_pg_largeobject_metadata form_lo_meta;
2283 char loname[NAMEDATALEN];
2284 Datum aclDatum;
2285 bool isNull;
2286 AclMode avail_goptions;
2287 AclMode this_privileges;
2288 Acl *old_acl;
2289 Acl *new_acl;
2290 Oid grantorId;
2291 Oid ownerId;
2292 HeapTuple newtuple;
2293 Datum values[Natts_pg_largeobject_metadata] = {0};
2294 bool nulls[Natts_pg_largeobject_metadata] = {0};
2295 bool replaces[Natts_pg_largeobject_metadata] = {0};
2296 int noldmembers;
2297 int nnewmembers;
2298 Oid *oldmembers;
2299 Oid *newmembers;
2300 ScanKeyData entry[1];
2301 SysScanDesc scan;
2302 HeapTuple tuple;
2303
2304 /* There's no syscache for pg_largeobject_metadata */
2305 ScanKeyInit(&entry[0],
2306 Anum_pg_largeobject_metadata_oid,
2307 BTEqualStrategyNumber, F_OIDEQ,
2308 ObjectIdGetDatum(loid));
2309
2310 scan = systable_beginscan(relation,
2311 LargeObjectMetadataOidIndexId, true,
2312 NULL, 1, entry);
2313
2314 tuple = systable_getnext(scan);
2315 if (!HeapTupleIsValid(tuple))
2316 elog(ERROR, "could not find tuple for large object %u", loid);
2317
2318 form_lo_meta = (Form_pg_largeobject_metadata) GETSTRUCT(tuple);
2319
2320 /*
2321 * Get owner ID and working copy of existing ACL. If there's no ACL,
2322 * substitute the proper default.
2323 */
2324 ownerId = form_lo_meta->lomowner;
2325 aclDatum = heap_getattr(tuple,
2326 Anum_pg_largeobject_metadata_lomacl,
2327 RelationGetDescr(relation), &isNull);
2328 if (isNull)
2329 {
2330 old_acl = acldefault(OBJECT_LARGEOBJECT, ownerId);
2331 /* There are no old member roles according to the catalogs */
2332 noldmembers = 0;
2333 oldmembers = NULL;
2334 }
2335 else
2336 {
2337 old_acl = DatumGetAclPCopy(aclDatum);
2338 /* Get the roles mentioned in the existing ACL */
2339 noldmembers = aclmembers(old_acl, &oldmembers);
2340 }
2341
2342 /* Determine ID to do the grant as, and available grant options */
2343 select_best_grantor(GetUserId(), istmt->privileges,
2344 old_acl, ownerId,
2345 &grantorId, &avail_goptions);
2346
2347 /*
2348 * Restrict the privileges to what we can actually grant, and emit the
2349 * standards-mandated warning and error messages.
2350 */
2351 snprintf(loname, sizeof(loname), "large object %u", loid);
2352 this_privileges =
2353 restrict_and_check_grant(istmt->is_grant, avail_goptions,
2354 istmt->all_privs, istmt->privileges,
2355 loid, grantorId, OBJECT_LARGEOBJECT,
2356 loname, 0, NULL);
2357
2358 /*
2359 * Generate new ACL.
2360 */
2361 new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
2362 istmt->grant_option, istmt->behavior,
2363 istmt->grantees, this_privileges,
2364 grantorId, ownerId);
2365
2366 /*
2367 * We need the members of both old and new ACLs so we can correct the
2368 * shared dependency information.
2369 */
2370 nnewmembers = aclmembers(new_acl, &newmembers);
2371
2372 /* finished building new ACL value, now insert it */
2373 replaces[Anum_pg_largeobject_metadata_lomacl - 1] = true;
2374 values[Anum_pg_largeobject_metadata_lomacl - 1]
2375 = PointerGetDatum(new_acl);
2376
2377 newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation),
2378 values, nulls, replaces);
2379
2380 CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
2381
2382 /* Update initial privileges for extensions */
2383 recordExtensionInitPriv(loid, LargeObjectRelationId, 0, new_acl);
2384
2385 /* Update the shared dependency ACL info */
2386 updateAclDependencies(LargeObjectRelationId,
2387 form_lo_meta->oid, 0,
2388 ownerId,
2389 noldmembers, oldmembers,
2390 nnewmembers, newmembers);
2391
2392 systable_endscan(scan);
2393
2394 pfree(new_acl);
2395
2396 /* prevent error when processing duplicate objects */
2397 CommandCounterIncrement();
2398 }
2399
2400 table_close(relation, RowExclusiveLock);
2401 }
2402
2403 static void
2404 ExecGrant_Type_check(InternalGrant *istmt, HeapTuple tuple)
2405 {
2406 Form_pg_type pg_type_tuple;
2407
2408 pg_type_tuple = (Form_pg_type) GETSTRUCT(tuple);
2409
2410 /* Disallow GRANT on dependent types */
2411 if (IsTrueArrayType(pg_type_tuple))
2412 ereport(ERROR,
2413 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
2414 errmsg("cannot set privileges of array types"),
2415 errhint("Set the privileges of the element type instead.")));
2416 if (pg_type_tuple->typtype == TYPTYPE_MULTIRANGE)
2417 ereport(ERROR,
2418 (errcode(ERRCODE_INVALID_GRANT_OPERATION),
2419 errmsg("cannot set privileges of multirange types"),
2420 errhint("Set the privileges of the range type instead.")));
2421 }
2422
2423 static void
2424 ExecGrant_Parameter(InternalGrant *istmt)
2425 {
2426 Relation relation;
2427 ListCell *cell;
2428
2429 if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
2430 istmt->privileges = ACL_ALL_RIGHTS_PARAMETER_ACL;
2431
2432 relation = table_open(ParameterAclRelationId, RowExclusiveLock);
2433
2434 foreach(cell, istmt->objects)
2435 {
2436 Oid parameterId = lfirst_oid(cell);
2437 Datum nameDatum;
2438 const char *parname;
2439 Datum aclDatum;
2440 bool isNull;
2441 AclMode avail_goptions;
2442 AclMode this_privileges;
2443 Acl *old_acl;
2444 Acl *new_acl;
2445 Oid grantorId;
2446 Oid ownerId;
2447 HeapTuple tuple;
2448 int noldmembers;
2449 int nnewmembers;
2450 Oid *oldmembers;
2451 Oid *newmembers;
2452
2453 tuple = SearchSysCache1(PARAMETERACLOID, ObjectIdGetDatum(parameterId));
2454 if (!HeapTupleIsValid(tuple))
2455 elog(ERROR, "cache lookup failed for parameter ACL %u",
2456 parameterId);
2457
2458 /* We'll need the GUC's name */
2459 nameDatum = SysCacheGetAttrNotNull(PARAMETERACLOID, tuple,
2460 Anum_pg_parameter_acl_parname);
2461 parname = TextDatumGetCString(nameDatum);
2462
2463 /* Treat all parameters as belonging to the bootstrap superuser. */
2464 ownerId = BOOTSTRAP_SUPERUSERID;
2465
2466 /*
2467 * Get working copy of existing ACL. If there's no ACL, substitute the
2468 * proper default.
2469 */
2470 aclDatum = SysCacheGetAttr(PARAMETERACLOID, tuple,
2471 Anum_pg_parameter_acl_paracl,
2472 &isNull);
2473
2474 if (isNull)
2475 {
2476 old_acl = acldefault(istmt->objtype, ownerId);
2477 /* There are no old member roles according to the catalogs */
2478 noldmembers = 0;
2479 oldmembers = NULL;
2480 }
2481 else
2482 {
2483 old_acl = DatumGetAclPCopy(aclDatum);
2484 /* Get the roles mentioned in the existing ACL */
2485 noldmembers = aclmembers(old_acl, &oldmembers);
2486 }
2487
2488 /* Determine ID to do the grant as, and available grant options */
2489 select_best_grantor(GetUserId(), istmt->privileges,
2490 old_acl, ownerId,
2491 &grantorId, &avail_goptions);
2492
2493 /*
2494 * Restrict the privileges to what we can actually grant, and emit the
2495 * standards-mandated warning and error messages.
2496 */
2497 this_privileges =
2498 restrict_and_check_grant(istmt->is_grant, avail_goptions,
2499 istmt->all_privs, istmt->privileges,
2500 parameterId, grantorId,
2501 OBJECT_PARAMETER_ACL,
2502 parname,
2503 0, NULL);
2504
2505 /*
2506 * Generate new ACL.
2507 */
2508 new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
2509 istmt->grant_option, istmt->behavior,
2510 istmt->grantees, this_privileges,
2511 grantorId, ownerId);
2512
2513 /*
2514 * We need the members of both old and new ACLs so we can correct the
2515 * shared dependency information.
2516 */
2517 nnewmembers = aclmembers(new_acl, &newmembers);
2518
2519 /*
2520 * If the new ACL is equal to the default, we don't need the catalog
2521 * entry any longer. Delete it rather than updating it, to avoid
2522 * leaving a degenerate entry.
2523 */
2524 if (aclequal(new_acl, acldefault(istmt->objtype, ownerId)))
2525 {
2526 CatalogTupleDelete(relation, &tuple->t_self);
2527 }
2528 else
2529 {
2530 /* finished building new ACL value, now insert it */
2531 HeapTuple newtuple;
2532 Datum values[Natts_pg_parameter_acl] = {0};
2533 bool nulls[Natts_pg_parameter_acl] = {0};
2534 bool replaces[Natts_pg_parameter_acl] = {0};
2535
2536 replaces[Anum_pg_parameter_acl_paracl - 1] = true;
2537 values[Anum_pg_parameter_acl_paracl - 1] = PointerGetDatum(new_acl);
2538
2539 newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation),
2540 values, nulls, replaces);
2541
2542 CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
2543 }
2544
2545 /* Update initial privileges for extensions */
2546 recordExtensionInitPriv(parameterId, ParameterAclRelationId, 0,
2547 new_acl);
2548
2549 /* Update the shared dependency ACL info */
2550 updateAclDependencies(ParameterAclRelationId, parameterId, 0,
2551 ownerId,
2552 noldmembers, oldmembers,
2553 nnewmembers, newmembers);
2554
2555 ReleaseSysCache(tuple);
2556 pfree(new_acl);
2557
2558 /* prevent error when processing duplicate objects */
2559 CommandCounterIncrement();
2560 }
2561
2562 table_close(relation, RowExclusiveLock);
2563 }
2564
2565
2566 static AclMode
2567 string_to_privilege(const char *privname)
2568 {
2569 if (strcmp(privname, "insert") == 0)
2570 return ACL_INSERT;
2571 if (strcmp(privname, "select") == 0)
2572 return ACL_SELECT;
2573 if (strcmp(privname, "update") == 0)
2574 return ACL_UPDATE;
2575 if (strcmp(privname, "delete") == 0)
2576 return ACL_DELETE;
2577 if (strcmp(privname, "truncate") == 0)
2578 return ACL_TRUNCATE;
2579 if (strcmp(privname, "references") == 0)
2580 return ACL_REFERENCES;
2581 if (strcmp(privname, "trigger") == 0)
2582 return ACL_TRIGGER;
2583 if (strcmp(privname, "execute") == 0)
2584 return ACL_EXECUTE;
2585 if (strcmp(privname, "usage") == 0)
2586 return ACL_USAGE;
2587 if (strcmp(privname, "create") == 0)
2588 return ACL_CREATE;
2589 if (strcmp(privname, "temporary") == 0)
2590 return ACL_CREATE_TEMP;
2591 if (strcmp(privname, "temp") == 0)
2592 return ACL_CREATE_TEMP;
2593 if (strcmp(privname, "connect") == 0)
2594 return ACL_CONNECT;
2595 if (strcmp(privname, "set") == 0)
2596 return ACL_SET;
2597 if (strcmp(privname, "alter system") == 0)
2598 return ACL_ALTER_SYSTEM;
2599 if (strcmp(privname, "maintain") == 0)
2600 return ACL_MAINTAIN;
2601 ereport(ERROR,
2602 (errcode(ERRCODE_SYNTAX_ERROR),
2603 errmsg("unrecognized privilege type \"%s\"", privname)));
2604 return 0; /* appease compiler */
2605 }
2606
2607 static const char *
2608 privilege_to_string(AclMode privilege)
2609 {
2610 switch (privilege)
2611 {
2612 case ACL_INSERT:
2613 return "INSERT";
2614 case ACL_SELECT:
2615 return "SELECT";
2616 case ACL_UPDATE:
2617 return "UPDATE";
2618 case ACL_DELETE:
2619 return "DELETE";
2620 case ACL_TRUNCATE:
2621 return "TRUNCATE";
2622 case ACL_REFERENCES:
2623 return "REFERENCES";
2624 case ACL_TRIGGER:
2625 return "TRIGGER";
2626 case ACL_EXECUTE:
2627 return "EXECUTE";
2628 case ACL_USAGE:
2629 return "USAGE";
2630 case ACL_CREATE:
2631 return "CREATE";
2632 case ACL_CREATE_TEMP:
2633 return "TEMP";
2634 case ACL_CONNECT:
2635 return "CONNECT";
2636 case ACL_SET:
2637 return "SET";
2638 case ACL_ALTER_SYSTEM:
2639 return "ALTER SYSTEM";
2640 case ACL_MAINTAIN:
2641 return "MAINTAIN";
2642 default:
2643 elog(ERROR, "unrecognized privilege: %d", (int) privilege);
2644 }
2645 return NULL; /* appease compiler */
2646 }
2647
2648 /*
2649 * Standardized reporting of aclcheck permissions failures.
2650 *
2651 * Note: we do not double-quote the %s's below, because many callers
2652 * supply strings that might be already quoted.
2653 */
2654 void
2655 aclcheck_error(AclResult aclerr, ObjectType objtype,
2656 const char *objectname)
2657 {
2658 switch (aclerr)
2659 {
2660 case ACLCHECK_OK:
2661 /* no error, so return to caller */
2662 break;
2663 case ACLCHECK_NO_PRIV:
2664 {
2665 const char *msg = "???";
2666
2667 switch (objtype)
2668 {
2669 case OBJECT_AGGREGATE:
2670 msg = gettext_noop("permission denied for aggregate %s");
2671 break;
2672 case OBJECT_COLLATION:
2673 msg = gettext_noop("permission denied for collation %s");
2674 break;
2675 case OBJECT_COLUMN:
2676 msg = gettext_noop("permission denied for column %s");
2677 break;
2678 case OBJECT_CONVERSION:
2679 msg = gettext_noop("permission denied for conversion %s");
2680 break;
2681 case OBJECT_DATABASE:
2682 msg = gettext_noop("permission denied for database %s");
2683 break;
2684 case OBJECT_DOMAIN:
2685 msg = gettext_noop("permission denied for domain %s");
2686 break;
2687 case OBJECT_EVENT_TRIGGER:
2688 msg = gettext_noop("permission denied for event trigger %s");
2689 break;
2690 case OBJECT_EXTENSION:
2691 msg = gettext_noop("permission denied for extension %s");
2692 break;
2693 case OBJECT_FDW:
2694 msg = gettext_noop("permission denied for foreign-data wrapper %s");
2695 break;
2696 case OBJECT_FOREIGN_SERVER:
2697 msg = gettext_noop("permission denied for foreign server %s");
2698 break;
2699 case OBJECT_FOREIGN_TABLE:
2700 msg = gettext_noop("permission denied for foreign table %s");
2701 break;
2702 case OBJECT_FUNCTION:
2703 msg = gettext_noop("permission denied for function %s");
2704 break;
2705 case OBJECT_INDEX:
2706 msg = gettext_noop("permission denied for index %s");
2707 break;
2708 case OBJECT_LANGUAGE:
2709 msg = gettext_noop("permission denied for language %s");
2710 break;
2711 case OBJECT_LARGEOBJECT:
2712 msg = gettext_noop("permission denied for large object %s");
2713 break;
2714 case OBJECT_MATVIEW:
2715 msg = gettext_noop("permission denied for materialized view %s");
2716 break;
2717 case OBJECT_OPCLASS:
2718 msg = gettext_noop("permission denied for operator class %s");
2719 break;
2720 case OBJECT_OPERATOR:
2721 msg = gettext_noop("permission denied for operator %s");
2722 break;
2723 case OBJECT_OPFAMILY:
2724 msg = gettext_noop("permission denied for operator family %s");
2725 break;
2726 case OBJECT_PARAMETER_ACL:
2727 msg = gettext_noop("permission denied for parameter %s");
2728 break;
2729 case OBJECT_POLICY:
2730 msg = gettext_noop("permission denied for policy %s");
2731 break;
2732 case OBJECT_PROCEDURE:
2733 msg = gettext_noop("permission denied for procedure %s");
2734 break;
2735 case OBJECT_PUBLICATION:
2736 msg = gettext_noop("permission denied for publication %s");
2737 break;
2738 case OBJECT_ROUTINE:
2739 msg = gettext_noop("permission denied for routine %s");
2740 break;
2741 case OBJECT_SCHEMA:
2742 msg = gettext_noop("permission denied for schema %s");
2743 break;
2744 case OBJECT_SEQUENCE:
2745 msg = gettext_noop("permission denied for sequence %s");
2746 break;
2747 case OBJECT_STATISTIC_EXT:
2748 msg = gettext_noop("permission denied for statistics object %s");
2749 break;
2750 case OBJECT_SUBSCRIPTION:
2751 msg = gettext_noop("permission denied for subscription %s");
2752 break;
2753 case OBJECT_TABLE:
2754 msg = gettext_noop("permission denied for table %s");
2755 break;
2756 case OBJECT_TABLESPACE:
2757 msg = gettext_noop("permission denied for tablespace %s");
2758 break;
2759 case OBJECT_TSCONFIGURATION:
2760 msg = gettext_noop("permission denied for text search configuration %s");
2761 break;
2762 case OBJECT_TSDICTIONARY:
2763 msg = gettext_noop("permission denied for text search dictionary %s");
2764 break;
2765 case OBJECT_TYPE:
2766 msg = gettext_noop("permission denied for type %s");
2767 break;
2768 case OBJECT_VIEW:
2769 msg = gettext_noop("permission denied for view %s");
2770 break;
2771 /* these currently aren't used */
2772 case OBJECT_ACCESS_METHOD:
2773 case OBJECT_AMOP:
2774 case OBJECT_AMPROC:
2775 case OBJECT_ATTRIBUTE:
2776 case OBJECT_CAST:
2777 case OBJECT_DEFAULT:
2778 case OBJECT_DEFACL:
2779 case OBJECT_DOMCONSTRAINT:
2780 case OBJECT_PUBLICATION_NAMESPACE:
2781 case OBJECT_PUBLICATION_REL:
2782 case OBJECT_ROLE:
2783 case OBJECT_RULE:
2784 case OBJECT_TABCONSTRAINT:
2785 case OBJECT_TRANSFORM:
2786 case OBJECT_TRIGGER:
2787 case OBJECT_TSPARSER:
2788 case OBJECT_TSTEMPLATE:
2789 case OBJECT_USER_MAPPING:
2790 elog(ERROR, "unsupported object type: %d", objtype);
2791 }
2792
2793 ereport(ERROR,
2794 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2795 errmsg(msg, objectname)));
2796 break;
2797 }
2798 case ACLCHECK_NOT_OWNER:
2799 {
2800 const char *msg = "???";
2801
2802 switch (objtype)
2803 {
2804 case OBJECT_AGGREGATE:
2805 msg = gettext_noop("must be owner of aggregate %s");
2806 break;
2807 case OBJECT_COLLATION:
2808 msg = gettext_noop("must be owner of collation %s");
2809 break;
2810 case OBJECT_CONVERSION:
2811 msg = gettext_noop("must be owner of conversion %s");
2812 break;
2813 case OBJECT_DATABASE:
2814 msg = gettext_noop("must be owner of database %s");
2815 break;
2816 case OBJECT_DOMAIN:
2817 msg = gettext_noop("must be owner of domain %s");
2818 break;
2819 case OBJECT_EVENT_TRIGGER:
2820 msg = gettext_noop("must be owner of event trigger %s");
2821 break;
2822 case OBJECT_EXTENSION:
2823 msg = gettext_noop("must be owner of extension %s");
2824 break;
2825 case OBJECT_FDW:
2826 msg = gettext_noop("must be owner of foreign-data wrapper %s");
2827 break;
2828 case OBJECT_FOREIGN_SERVER:
2829 msg = gettext_noop("must be owner of foreign server %s");
2830 break;
2831 case OBJECT_FOREIGN_TABLE:
2832 msg = gettext_noop("must be owner of foreign table %s");
2833 break;
2834 case OBJECT_FUNCTION:
2835 msg = gettext_noop("must be owner of function %s");
2836 break;
2837 case OBJECT_INDEX:
2838 msg = gettext_noop("must be owner of index %s");
2839 break;
2840 case OBJECT_LANGUAGE:
2841 msg = gettext_noop("must be owner of language %s");
2842 break;
2843 case OBJECT_LARGEOBJECT:
2844 msg = gettext_noop("must be owner of large object %s");
2845 break;
2846 case OBJECT_MATVIEW:
2847 msg = gettext_noop("must be owner of materialized view %s");
2848 break;
2849 case OBJECT_OPCLASS:
2850 msg = gettext_noop("must be owner of operator class %s");
2851 break;
2852 case OBJECT_OPERATOR:
2853 msg = gettext_noop("must be owner of operator %s");
2854 break;
2855 case OBJECT_OPFAMILY:
2856 msg = gettext_noop("must be owner of operator family %s");
2857 break;
2858 case OBJECT_PROCEDURE:
2859 msg = gettext_noop("must be owner of procedure %s");
2860 break;
2861 case OBJECT_PUBLICATION:
2862 msg = gettext_noop("must be owner of publication %s");
2863 break;
2864 case OBJECT_ROUTINE:
2865 msg = gettext_noop("must be owner of routine %s");
2866 break;
2867 case OBJECT_SEQUENCE:
2868 msg = gettext_noop("must be owner of sequence %s");
2869 break;
2870 case OBJECT_SUBSCRIPTION:
2871 msg = gettext_noop("must be owner of subscription %s");
2872 break;
2873 case OBJECT_TABLE:
2874 msg = gettext_noop("must be owner of table %s");
2875 break;
2876 case OBJECT_TYPE:
2877 msg = gettext_noop("must be owner of type %s");
2878 break;
2879 case OBJECT_VIEW:
2880 msg = gettext_noop("must be owner of view %s");
2881 break;
2882 case OBJECT_SCHEMA:
2883 msg = gettext_noop("must be owner of schema %s");
2884 break;
2885 case OBJECT_STATISTIC_EXT:
2886 msg = gettext_noop("must be owner of statistics object %s");
2887 break;
2888 case OBJECT_TABLESPACE:
2889 msg = gettext_noop("must be owner of tablespace %s");
2890 break;
2891 case OBJECT_TSCONFIGURATION:
2892 msg = gettext_noop("must be owner of text search configuration %s");
2893 break;
2894 case OBJECT_TSDICTIONARY:
2895 msg = gettext_noop("must be owner of text search dictionary %s");
2896 break;
2897
2898 /*
2899 * Special cases: For these, the error message talks
2900 * about "relation", because that's where the
2901 * ownership is attached. See also
2902 * check_object_ownership().
2903 */
2904 case OBJECT_COLUMN:
2905 case OBJECT_POLICY:
2906 case OBJECT_RULE:
2907 case OBJECT_TABCONSTRAINT:
2908 case OBJECT_TRIGGER:
2909 msg = gettext_noop("must be owner of relation %s");
2910 break;
2911 /* these currently aren't used */
2912 case OBJECT_ACCESS_METHOD:
2913 case OBJECT_AMOP:
2914 case OBJECT_AMPROC:
2915 case OBJECT_ATTRIBUTE:
2916 case OBJECT_CAST:
2917 case OBJECT_DEFAULT:
2918 case OBJECT_DEFACL:
2919 case OBJECT_DOMCONSTRAINT:
2920 case OBJECT_PARAMETER_ACL:
2921 case OBJECT_PUBLICATION_NAMESPACE:
2922 case OBJECT_PUBLICATION_REL:
2923 case OBJECT_ROLE:
2924 case OBJECT_TRANSFORM:
2925 case OBJECT_TSPARSER:
2926 case OBJECT_TSTEMPLATE:
2927 case OBJECT_USER_MAPPING:
2928 elog(ERROR, "unsupported object type: %d", objtype);
2929 }
2930
2931 ereport(ERROR,
2932 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2933 errmsg(msg, objectname)));
2934 break;
2935 }
2936 default:
2937 elog(ERROR, "unrecognized AclResult: %d", (int) aclerr);
2938 break;
2939 }
2940 }
2941
2942
2943 void
2944 aclcheck_error_col(AclResult aclerr, ObjectType objtype,
2945 const char *objectname, const char *colname)
2946 {
2947 switch (aclerr)
2948 {
2949 case ACLCHECK_OK:
2950 /* no error, so return to caller */
2951 break;
2952 case ACLCHECK_NO_PRIV:
2953 ereport(ERROR,
2954 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2955 errmsg("permission denied for column \"%s\" of relation \"%s\"",
2956 colname, objectname)));
2957 break;
2958 case ACLCHECK_NOT_OWNER:
2959 /* relation msg is OK since columns don't have separate owners */
2960 aclcheck_error(aclerr, objtype, objectname);
2961 break;
2962 default:
2963 elog(ERROR, "unrecognized AclResult: %d", (int) aclerr);
2964 break;
2965 }
2966 }
2967
2968
2969 /*
2970 * Special common handling for types: use element type instead of array type,
2971 * and format nicely
2972 */
2973 void
2974 aclcheck_error_type(AclResult aclerr, Oid typeOid)
2975 {
2976 Oid element_type = get_element_type(typeOid);
2977
2978 aclcheck_error(aclerr, OBJECT_TYPE, format_type_be(element_type ? element_type : typeOid));
2979 }
2980
2981
2982 /*
2983 * Relay for the various pg_*_mask routines depending on object kind
2984 */
2985 static AclMode
2986 pg_aclmask(ObjectType objtype, Oid object_oid, AttrNumber attnum, Oid roleid,
2987 AclMode mask, AclMaskHow how)
2988 {
2989 switch (objtype)
2990 {
2991 case OBJECT_COLUMN:
2992 return
2993 pg_class_aclmask(object_oid, roleid, mask, how) |
2994 pg_attribute_aclmask(object_oid, attnum, roleid, mask, how);
2995 case OBJECT_TABLE:
2996 case OBJECT_SEQUENCE:
2997 return pg_class_aclmask(object_oid, roleid, mask, how);
2998 case OBJECT_DATABASE:
2999 return object_aclmask(DatabaseRelationId, object_oid, roleid, mask, how);
3000 case OBJECT_FUNCTION:
3001 return object_aclmask(ProcedureRelationId, object_oid, roleid, mask, how);
3002 case OBJECT_LANGUAGE:
3003 return object_aclmask(LanguageRelationId, object_oid, roleid, mask, how);
3004 case OBJECT_LARGEOBJECT:
3005 return pg_largeobject_aclmask_snapshot(object_oid, roleid,
3006 mask, how, NULL);
3007 case OBJECT_PARAMETER_ACL:
3008 return pg_parameter_acl_aclmask(object_oid, roleid, mask, how);
3009 case OBJECT_SCHEMA:
3010 return object_aclmask(NamespaceRelationId, object_oid, roleid, mask, how);
3011 case OBJECT_STATISTIC_EXT:
3012 elog(ERROR, "grantable rights not supported for statistics objects");
3013 /* not reached, but keep compiler quiet */
3014 return ACL_NO_RIGHTS;
3015 case OBJECT_TABLESPACE:
3016 return object_aclmask(TableSpaceRelationId, object_oid, roleid, mask, how);
3017 case OBJECT_FDW:
3018 return object_aclmask(ForeignDataWrapperRelationId, object_oid, roleid, mask, how);
3019 case OBJECT_FOREIGN_SERVER:
3020 return object_aclmask(ForeignServerRelationId, object_oid, roleid, mask, how);
3021 case OBJECT_EVENT_TRIGGER:
3022 elog(ERROR, "grantable rights not supported for event triggers");
3023 /* not reached, but keep compiler quiet */
3024 return ACL_NO_RIGHTS;
3025 case OBJECT_TYPE:
3026 return object_aclmask(TypeRelationId, object_oid, roleid, mask, how);
3027 default:
3028 elog(ERROR, "unrecognized object type: %d",
3029 (int) objtype);
3030 /* not reached, but keep compiler quiet */
3031 return ACL_NO_RIGHTS;
3032 }
3033 }
3034
3035
3036 /* ****************************************************************
3037 * Exported routines for examining a user's privileges for various objects
3038 *
3039 * See aclmask() for a description of the common API for these functions.
3040 * ****************************************************************
3041 */
3042
3043 /*
3044 * Generic routine for examining a user's privileges for an object
3045 */
3046 static AclMode
3047 object_aclmask(Oid classid, Oid objectid, Oid roleid,
3048 AclMode mask, AclMaskHow how)
3049 {
3050 return object_aclmask_ext(classid, objectid, roleid, mask, how, NULL);
3051 }
3052
3053 /*
3054 * Generic routine for examining a user's privileges for an object,
3055 * with is_missing
3056 */
3057 static AclMode
3058 object_aclmask_ext(Oid classid, Oid objectid, Oid roleid,
3059 AclMode mask, AclMaskHow how,
3060 bool *is_missing)
3061 {
3062 int cacheid;
3063 AclMode result;
3064 HeapTuple tuple;
3065 Datum aclDatum;
3066 bool isNull;
3067 Acl *acl;
3068 Oid ownerId;
3069
3070 /* Special cases */
3071 switch (classid)
3072 {
3073 case NamespaceRelationId:
3074 return pg_namespace_aclmask_ext(objectid, roleid, mask, how,
3075 is_missing);
3076 case TypeRelationId:
3077 return pg_type_aclmask_ext(objectid, roleid, mask, how,
3078 is_missing);
3079 }
3080
3081 /* Even more special cases */
3082 Assert(classid != RelationRelationId); /* should use pg_class_acl* */
3083 Assert(classid != LargeObjectMetadataRelationId); /* should use
3084 * pg_largeobject_acl* */
3085
3086 /* Superusers bypass all permission checking. */
3087 if (superuser_arg(roleid))
3088 return mask;
3089
3090 /*
3091 * Get the object's ACL from its catalog
3092 */
3093
3094 cacheid = get_object_catcache_oid(classid);
3095
3096 tuple = SearchSysCache1(cacheid, ObjectIdGetDatum(objectid));
3097 if (!HeapTupleIsValid(tuple))
3098 {
3099 if (is_missing != NULL)
3100 {
3101 /* return "no privileges" instead of throwing an error */
3102 *is_missing = true;
3103 return 0;
3104 }
3105 else
3106 elog(ERROR, "cache lookup failed for %s %u",
3107 get_object_class_descr(classid), objectid);
3108 }
3109
3110 ownerId = DatumGetObjectId(SysCacheGetAttrNotNull(cacheid,
3111 tuple,
3112 get_object_attnum_owner(classid)));
3113
3114 aclDatum = SysCacheGetAttr(cacheid, tuple, get_object_attnum_acl(classid),
3115 &isNull);
3116 if (isNull)
3117 {
3118 /* No ACL, so build default ACL */
3119 acl = acldefault(get_object_type(classid, objectid), ownerId);
3120 aclDatum = (Datum) 0;
3121 }
3122 else
3123 {
3124 /* detoast ACL if necessary */
3125 acl = DatumGetAclP(aclDatum);
3126 }
3127
3128 result = aclmask(acl, roleid, ownerId, mask, how);
3129
3130 /* if we have a detoasted copy, free it */
3131 if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
3132 pfree(acl);
3133
3134 ReleaseSysCache(tuple);
3135
3136 return result;
3137 }
3138
3139 /*
3140 * Routine for examining a user's privileges for a column
3141 *
3142 * Note: this considers only privileges granted specifically on the column.
3143 * It is caller's responsibility to take relation-level privileges into account
3144 * as appropriate. (For the same reason, we have no special case for
3145 * superuser-ness here.)
3146 */
3147 static AclMode
3148 pg_attribute_aclmask(Oid table_oid, AttrNumber attnum, Oid roleid,
3149 AclMode mask, AclMaskHow how)
3150 {
3151 return pg_attribute_aclmask_ext(table_oid, attnum, roleid,
3152 mask, how, NULL);
3153 }
3154
3155 /*
3156 * Routine for examining a user's privileges for a column, with is_missing
3157 */
3158 static AclMode
3159 pg_attribute_aclmask_ext(Oid table_oid, AttrNumber attnum, Oid roleid,
3160 AclMode mask, AclMaskHow how, bool *is_missing)
3161 {
3162 AclMode result;
3163 HeapTuple classTuple;
3164 HeapTuple attTuple;
3165 Form_pg_class classForm;
3166 Form_pg_attribute attributeForm;
3167 Datum aclDatum;
3168 bool isNull;
3169 Acl *acl;
3170 Oid ownerId;
3171
3172 /*
3173 * First, get the column's ACL from its pg_attribute entry
3174 */
3175 attTuple = SearchSysCache2(ATTNUM,
3176 ObjectIdGetDatum(table_oid),
3177 Int16GetDatum(attnum));
3178 if (!HeapTupleIsValid(attTuple))
3179 {
3180 if (is_missing != NULL)
3181 {
3182 /* return "no privileges" instead of throwing an error */
3183 *is_missing = true;
3184 return 0;
3185 }
3186 else
3187 ereport(ERROR,
3188 (errcode(ERRCODE_UNDEFINED_COLUMN),
3189 errmsg("attribute %d of relation with OID %u does not exist",
3190 attnum, table_oid)));
3191 }
3192
3193 attributeForm = (Form_pg_attribute) GETSTRUCT(attTuple);
3194
3195 /* Check dropped columns, too */
3196 if (attributeForm->attisdropped)
3197 {
3198 if (is_missing != NULL)
3199 {
3200 /* return "no privileges" instead of throwing an error */
3201 *is_missing = true;
3202 ReleaseSysCache(attTuple);
3203 return 0;
3204 }
3205 else
3206 ereport(ERROR,
3207 (errcode(ERRCODE_UNDEFINED_COLUMN),
3208 errmsg("attribute %d of relation with OID %u does not exist",
3209 attnum, table_oid)));
3210 }
3211
3212 aclDatum = SysCacheGetAttr(ATTNUM, attTuple, Anum_pg_attribute_attacl,
3213 &isNull);
3214
3215 /*
3216 * Here we hard-wire knowledge that the default ACL for a column grants no
3217 * privileges, so that we can fall out quickly in the very common case
3218 * where attacl is null.
3219 */
3220 if (isNull)
3221 {
3222 ReleaseSysCache(attTuple);
3223 return 0;
3224 }
3225
3226 /*
3227 * Must get the relation's ownerId from pg_class. Since we already found
3228 * a pg_attribute entry, the only likely reason for this to fail is that a
3229 * concurrent DROP of the relation committed since then (which could only
3230 * happen if we don't have lock on the relation). Treat that similarly to
3231 * not finding the attribute entry.
3232 */
3233 classTuple = SearchSysCache1(RELOID, ObjectIdGetDatum(table_oid));
3234 if (!HeapTupleIsValid(classTuple))
3235 {
3236 ReleaseSysCache(attTuple);
3237 if (is_missing != NULL)
3238 {
3239 /* return "no privileges" instead of throwing an error */
3240 *is_missing = true;
3241 return 0;
3242 }
3243 else
3244 ereport(ERROR,
3245 (errcode(ERRCODE_UNDEFINED_TABLE),
3246 errmsg("relation with OID %u does not exist",
3247 table_oid)));
3248 }
3249 classForm = (Form_pg_class) GETSTRUCT(classTuple);
3250
3251 ownerId = classForm->relowner;
3252
3253 ReleaseSysCache(classTuple);
3254
3255 /* detoast column's ACL if necessary */
3256 acl = DatumGetAclP(aclDatum);
3257
3258 result = aclmask(acl, roleid, ownerId, mask, how);
3259
3260 /* if we have a detoasted copy, free it */
3261 if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
3262 pfree(acl);
3263
3264 ReleaseSysCache(attTuple);
3265
3266 return result;
3267 }
3268
3269 /*
3270 * Exported routine for examining a user's privileges for a table
3271 */
3272 AclMode
3273 pg_class_aclmask(Oid table_oid, Oid roleid,
3274 AclMode mask, AclMaskHow how)
3275 {
3276 return pg_class_aclmask_ext(table_oid, roleid, mask, how, NULL);
3277 }
3278
3279 /*
3280 * Routine for examining a user's privileges for a table, with is_missing
3281 */
3282 static AclMode
3283 pg_class_aclmask_ext(Oid table_oid, Oid roleid, AclMode mask,
3284 AclMaskHow how, bool *is_missing)
3285 {
3286 AclMode result;
3287 HeapTuple tuple;
3288 Form_pg_class classForm;
3289 Datum aclDatum;
3290 bool isNull;
3291 Acl *acl;
3292 Oid ownerId;
3293
3294 /*
3295 * Must get the relation's tuple from pg_class
3296 */
3297 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(table_oid));
3298 if (!HeapTupleIsValid(tuple))
3299 {
3300 if (is_missing != NULL)
3301 {
3302 /* return "no privileges" instead of throwing an error */
3303 *is_missing = true;
3304 return 0;
3305 }
3306 else
3307 ereport(ERROR,
3308 (errcode(ERRCODE_UNDEFINED_TABLE),
3309 errmsg("relation with OID %u does not exist",
3310 table_oid)));
3311 }
3312
3313 classForm = (Form_pg_class) GETSTRUCT(tuple);
3314
3315 /*
3316 * Deny anyone permission to update a system catalog unless
3317 * pg_authid.rolsuper is set.
3318 *
3319 * As of 7.4 we have some updatable system views; those shouldn't be
3320 * protected in this way. Assume the view rules can take care of
3321 * themselves. ACL_USAGE is if we ever have system sequences.
3322 */
3323 if ((mask & (ACL_INSERT | ACL_UPDATE | ACL_DELETE | ACL_TRUNCATE | ACL_USAGE)) &&
3324 IsSystemClass(table_oid, classForm) &&
3325 classForm->relkind != RELKIND_VIEW &&
3326 !superuser_arg(roleid))
3327 mask &= ~(ACL_INSERT | ACL_UPDATE | ACL_DELETE | ACL_TRUNCATE | ACL_USAGE);
3328
3329 /*
3330 * Otherwise, superusers bypass all permission-checking.
3331 */
3332 if (superuser_arg(roleid))
3333 {
3334 ReleaseSysCache(tuple);
3335 return mask;
3336 }
3337
3338 /*
3339 * Normal case: get the relation's ACL from pg_class
3340 */
3341 ownerId = classForm->relowner;
3342
3343 aclDatum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relacl,
3344 &isNull);
3345 if (isNull)
3346 {
3347 /* No ACL, so build default ACL */
3348 switch (classForm->relkind)
3349 {
3350 case RELKIND_SEQUENCE:
3351 acl = acldefault(OBJECT_SEQUENCE, ownerId);
3352 break;
3353 default:
3354 acl = acldefault(OBJECT_TABLE, ownerId);
3355 break;
3356 }
3357 aclDatum = (Datum) 0;
3358 }
3359 else
3360 {
3361 /* detoast rel's ACL if necessary */
3362 acl = DatumGetAclP(aclDatum);
3363 }
3364
3365 result = aclmask(acl, roleid, ownerId, mask, how);
3366
3367 /* if we have a detoasted copy, free it */
3368 if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
3369 pfree(acl);
3370
3371 ReleaseSysCache(tuple);
3372
3373 /*
3374 * Check if ACL_SELECT is being checked and, if so, and not set already as
3375 * part of the result, then check if the user is a member of the
3376 * pg_read_all_data role, which allows read access to all relations.
3377 */
3378 if (mask & ACL_SELECT && !(result & ACL_SELECT) &&
3379 has_privs_of_role(roleid, ROLE_PG_READ_ALL_DATA))
3380 result |= ACL_SELECT;
3381
3382 /*
3383 * Check if ACL_INSERT, ACL_UPDATE, or ACL_DELETE is being checked and, if
3384 * so, and not set already as part of the result, then check if the user
3385 * is a member of the pg_write_all_data role, which allows
3386 * INSERT/UPDATE/DELETE access to all relations (except system catalogs,
3387 * which requires superuser, see above).
3388 */
3389 if (mask & (ACL_INSERT | ACL_UPDATE | ACL_DELETE) &&
3390 !(result & (ACL_INSERT | ACL_UPDATE | ACL_DELETE)) &&
3391 has_privs_of_role(roleid, ROLE_PG_WRITE_ALL_DATA))
3392 result |= (mask & (ACL_INSERT | ACL_UPDATE | ACL_DELETE));
3393
3394 /*
3395 * Check if ACL_MAINTAIN is being checked and, if so, and not already set
3396 * as part of the result, then check if the user is a member of the
3397 * pg_maintain role, which allows VACUUM, ANALYZE, CLUSTER, REFRESH
3398 * MATERIALIZED VIEW, REINDEX, and LOCK TABLE on all relations.
3399 */
3400 if (mask & ACL_MAINTAIN &&
3401 !(result & ACL_MAINTAIN) &&
3402 has_privs_of_role(roleid, ROLE_PG_MAINTAIN))
3403 result |= ACL_MAINTAIN;
3404
3405 return result;
3406 }
3407
3408 /*
3409 * Routine for examining a user's privileges for a configuration
3410 * parameter (GUC), identified by GUC name.
3411 */
3412 static AclMode
3413 pg_parameter_aclmask(const char *name, Oid roleid, AclMode mask, AclMaskHow how)
3414 {
3415 AclMode result;
3416 char *parname;
3417 text *partext;
3418 HeapTuple tuple;
3419
3420 /* Superusers bypass all permission checking. */
3421 if (superuser_arg(roleid))
3422 return mask;
3423
3424 /* Convert name to the form it should have in pg_parameter_acl... */
3425 parname = convert_GUC_name_for_parameter_acl(name);
3426 partext = cstring_to_text(parname);
3427
3428 /* ... and look it up */
3429 tuple = SearchSysCache1(PARAMETERACLNAME, PointerGetDatum(partext));
3430
3431 if (!HeapTupleIsValid(tuple))
3432 {
3433 /* If no entry, GUC has no permissions for non-superusers */
3434 result = ACL_NO_RIGHTS;
3435 }
3436 else
3437 {
3438 Datum aclDatum;
3439 bool isNull;
3440 Acl *acl;
3441
3442 aclDatum = SysCacheGetAttr(PARAMETERACLNAME, tuple,
3443 Anum_pg_parameter_acl_paracl,
3444 &isNull);
3445 if (isNull)
3446 {
3447 /* No ACL, so build default ACL */
3448 acl = acldefault(OBJECT_PARAMETER_ACL, BOOTSTRAP_SUPERUSERID);
3449 aclDatum = (Datum) 0;
3450 }
3451 else
3452 {
3453 /* detoast ACL if necessary */
3454 acl = DatumGetAclP(aclDatum);
3455 }
3456
3457 result = aclmask(acl, roleid, BOOTSTRAP_SUPERUSERID, mask, how);
3458
3459 /* if we have a detoasted copy, free it */
3460 if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
3461 pfree(acl);
3462
3463 ReleaseSysCache(tuple);
3464 }
3465
3466 pfree(parname);
3467 pfree(partext);
3468
3469 return result;
3470 }
3471
3472 /*
3473 * Routine for examining a user's privileges for a configuration
3474 * parameter (GUC), identified by the OID of its pg_parameter_acl entry.
3475 */
3476 static AclMode
3477 pg_parameter_acl_aclmask(Oid acl_oid, Oid roleid, AclMode mask, AclMaskHow how)
3478 {
3479 AclMode result;
3480 HeapTuple tuple;
3481 Datum aclDatum;
3482 bool isNull;
3483 Acl *acl;
3484
3485 /* Superusers bypass all permission checking. */
3486 if (superuser_arg(roleid))
3487 return mask;
3488
3489 /* Get the ACL from pg_parameter_acl */
3490 tuple = SearchSysCache1(PARAMETERACLOID, ObjectIdGetDatum(acl_oid));
3491 if (!HeapTupleIsValid(tuple))
3492 ereport(ERROR,
3493 (errcode(ERRCODE_UNDEFINED_OBJECT),
3494 errmsg("parameter ACL with OID %u does not exist",
3495 acl_oid)));
3496
3497 aclDatum = SysCacheGetAttr(PARAMETERACLOID, tuple,
3498 Anum_pg_parameter_acl_paracl,
3499 &isNull);
3500 if (isNull)
3501 {
3502 /* No ACL, so build default ACL */
3503 acl = acldefault(OBJECT_PARAMETER_ACL, BOOTSTRAP_SUPERUSERID);
3504 aclDatum = (Datum) 0;
3505 }
3506 else
3507 {
3508 /* detoast ACL if necessary */
3509 acl = DatumGetAclP(aclDatum);
3510 }
3511
3512 result = aclmask(acl, roleid, BOOTSTRAP_SUPERUSERID, mask, how);
3513
3514 /* if we have a detoasted copy, free it */
3515 if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
3516 pfree(acl);
3517
3518 ReleaseSysCache(tuple);
3519
3520 return result;
3521 }
3522
3523 /*
3524 * Routine for examining a user's privileges for a largeobject
3525 *
3526 * When a large object is opened for reading, it is opened relative to the
3527 * caller's snapshot, but when it is opened for writing, a current
3528 * MVCC snapshot will be used. See doc/src/sgml/lobj.sgml. This function
3529 * takes a snapshot argument so that the permissions check can be made
3530 * relative to the same snapshot that will be used to read the underlying
3531 * data. The caller will actually pass NULL for an instantaneous MVCC
3532 * snapshot, since all we do with the snapshot argument is pass it through
3533 * to systable_beginscan().
3534 */
3535 static AclMode
3536 pg_largeobject_aclmask_snapshot(Oid lobj_oid, Oid roleid,
3537 AclMode mask, AclMaskHow how,
3538 Snapshot snapshot)
3539 {
3540 AclMode result;
3541 Relation pg_lo_meta;
3542 ScanKeyData entry[1];
3543 SysScanDesc scan;
3544 HeapTuple tuple;
3545 Datum aclDatum;
3546 bool isNull;
3547 Acl *acl;
3548 Oid ownerId;
3549
3550 /* Superusers bypass all permission checking. */
3551 if (superuser_arg(roleid))
3552 return mask;
3553
3554 /*
3555 * Get the largeobject's ACL from pg_largeobject_metadata
3556 */
3557 pg_lo_meta = table_open(LargeObjectMetadataRelationId,
3558 AccessShareLock);
3559
3560 ScanKeyInit(&entry[0],
3561 Anum_pg_largeobject_metadata_oid,
3562 BTEqualStrategyNumber, F_OIDEQ,
3563 ObjectIdGetDatum(lobj_oid));
3564
3565 scan = systable_beginscan(pg_lo_meta,
3566 LargeObjectMetadataOidIndexId, true,
3567 snapshot, 1, entry);
3568
3569 tuple = systable_getnext(scan);
3570 if (!HeapTupleIsValid(tuple))
3571 ereport(ERROR,
3572 (errcode(ERRCODE_UNDEFINED_OBJECT),
3573 errmsg("large object %u does not exist", lobj_oid)));
3574
3575 ownerId = ((Form_pg_largeobject_metadata) GETSTRUCT(tuple))->lomowner;
3576
3577 aclDatum = heap_getattr(tuple, Anum_pg_largeobject_metadata_lomacl,
3578 RelationGetDescr(pg_lo_meta), &isNull);
3579
3580 if (isNull)
3581 {
3582 /* No ACL, so build default ACL */
3583 acl = acldefault(OBJECT_LARGEOBJECT, ownerId);
3584 aclDatum = (Datum) 0;
3585 }
3586 else
3587 {
3588 /* detoast ACL if necessary */
3589 acl = DatumGetAclP(aclDatum);
3590 }
3591
3592 result = aclmask(acl, roleid, ownerId, mask, how);
3593
3594 /* if we have a detoasted copy, free it */
3595 if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
3596 pfree(acl);
3597
3598 systable_endscan(scan);
3599
3600 table_close(pg_lo_meta, AccessShareLock);
3601
3602 return result;
3603 }
3604
3605 /*
3606 * Routine for examining a user's privileges for a namespace, with is_missing
3607 */
3608 static AclMode
3609 pg_namespace_aclmask_ext(Oid nsp_oid, Oid roleid,
3610 AclMode mask, AclMaskHow how,
3611 bool *is_missing)
3612 {
3613 AclMode result;
3614 HeapTuple tuple;
3615 Datum aclDatum;
3616 bool isNull;
3617 Acl *acl;
3618 Oid ownerId;
3619
3620 /* Superusers bypass all permission checking. */
3621 if (superuser_arg(roleid))
3622 return mask;
3623
3624 /*
3625 * If we have been assigned this namespace as a temp namespace, check to
3626 * make sure we have CREATE TEMP permission on the database, and if so act
3627 * as though we have all standard (but not GRANT OPTION) permissions on
3628 * the namespace. If we don't have CREATE TEMP, act as though we have
3629 * only USAGE (and not CREATE) rights.
3630 *
3631 * This may seem redundant given the check in InitTempTableNamespace, but
3632 * it really isn't since current user ID may have changed since then. The
3633 * upshot of this behavior is that a SECURITY DEFINER function can create
3634 * temp tables that can then be accessed (if permission is granted) by
3635 * code in the same session that doesn't have permissions to create temp
3636 * tables.
3637 *
3638 * XXX Would it be safe to ereport a special error message as
3639 * InitTempTableNamespace does? Returning zero here means we'll get a
3640 * generic "permission denied for schema pg_temp_N" message, which is not
3641 * remarkably user-friendly.
3642 */
3643 if (isTempNamespace(nsp_oid))
3644 {
3645 if (object_aclcheck_ext(DatabaseRelationId, MyDatabaseId, roleid,
3646 ACL_CREATE_TEMP, is_missing) == ACLCHECK_OK)
3647 return mask & ACL_ALL_RIGHTS_SCHEMA;
3648 else
3649 return mask & ACL_USAGE;
3650 }
3651
3652 /*
3653 * Get the schema's ACL from pg_namespace
3654 */
3655 tuple = SearchSysCache1(NAMESPACEOID, ObjectIdGetDatum(nsp_oid));
3656 if (!HeapTupleIsValid(tuple))
3657 {
3658 if (is_missing != NULL)
3659 {
3660 /* return "no privileges" instead of throwing an error */
3661 *is_missing = true;
3662 return 0;
3663 }
3664 else
3665 ereport(ERROR,
3666 (errcode(ERRCODE_UNDEFINED_SCHEMA),
3667 errmsg("schema with OID %u does not exist", nsp_oid)));
3668 }
3669
3670 ownerId = ((Form_pg_namespace) GETSTRUCT(tuple))->nspowner;
3671
3672 aclDatum = SysCacheGetAttr(NAMESPACEOID, tuple, Anum_pg_namespace_nspacl,
3673 &isNull);
3674 if (isNull)
3675 {
3676 /* No ACL, so build default ACL */
3677 acl = acldefault(OBJECT_SCHEMA, ownerId);
3678 aclDatum = (Datum) 0;
3679 }
3680 else
3681 {
3682 /* detoast ACL if necessary */
3683 acl = DatumGetAclP(aclDatum);
3684 }
3685
3686 result = aclmask(acl, roleid, ownerId, mask, how);
3687
3688 /* if we have a detoasted copy, free it */
3689 if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
3690 pfree(acl);
3691
3692 ReleaseSysCache(tuple);
3693
3694 /*
3695 * Check if ACL_USAGE is being checked and, if so, and not set already as
3696 * part of the result, then check if the user is a member of the
3697 * pg_read_all_data or pg_write_all_data roles, which allow usage access
3698 * to all schemas.
3699 */
3700 if (mask & ACL_USAGE && !(result & ACL_USAGE) &&
3701 (has_privs_of_role(roleid, ROLE_PG_READ_ALL_DATA) ||
3702 has_privs_of_role(roleid, ROLE_PG_WRITE_ALL_DATA)))
3703 result |= ACL_USAGE;
3704 return result;
3705 }
3706
3707 /*
3708 * Routine for examining a user's privileges for a type, with is_missing
3709 */
3710 static AclMode
3711 pg_type_aclmask_ext(Oid type_oid, Oid roleid, AclMode mask, AclMaskHow how,
3712 bool *is_missing)
3713 {
3714 AclMode result;
3715 HeapTuple tuple;
3716 Form_pg_type typeForm;
3717 Datum aclDatum;
3718 bool isNull;
3719 Acl *acl;
3720 Oid ownerId;
3721
3722 /* Bypass permission checks for superusers */
3723 if (superuser_arg(roleid))
3724 return mask;
3725
3726 /*
3727 * Must get the type's tuple from pg_type
3728 */
3729 tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type_oid));
3730 if (!HeapTupleIsValid(tuple))
3731 {
3732 if (is_missing != NULL)
3733 {
3734 /* return "no privileges" instead of throwing an error */
3735 *is_missing = true;
3736 return 0;
3737 }
3738 else
3739 ereport(ERROR,
3740 (errcode(ERRCODE_UNDEFINED_OBJECT),
3741 errmsg("type with OID %u does not exist",
3742 type_oid)));
3743 }
3744 typeForm = (Form_pg_type) GETSTRUCT(tuple);
3745
3746 /*
3747 * "True" array types don't manage permissions of their own; consult the
3748 * element type instead.
3749 */
3750 if (IsTrueArrayType(typeForm))
3751 {
3752 Oid elttype_oid = typeForm->typelem;
3753
3754 ReleaseSysCache(tuple);
3755
3756 tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(elttype_oid));
3757 if (!HeapTupleIsValid(tuple))
3758 {
3759 if (is_missing != NULL)
3760 {
3761 /* return "no privileges" instead of throwing an error */
3762 *is_missing = true;
3763 return 0;
3764 }
3765 else
3766 ereport(ERROR,
3767 (errcode(ERRCODE_UNDEFINED_OBJECT),
3768 errmsg("type with OID %u does not exist",
3769 elttype_oid)));
3770 }
3771 typeForm = (Form_pg_type) GETSTRUCT(tuple);
3772 }
3773
3774 /*
3775 * Likewise, multirange types don't manage their own permissions; consult
3776 * the associated range type. (Note we must do this after the array step
3777 * to get the right answer for arrays of multiranges.)
3778 */
3779 if (typeForm->typtype == TYPTYPE_MULTIRANGE)
3780 {
3781 Oid rangetype = get_multirange_range(typeForm->oid);
3782
3783 ReleaseSysCache(tuple);
3784
3785 tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rangetype));
3786 if (!HeapTupleIsValid(tuple))
3787 {
3788 if (is_missing != NULL)
3789 {
3790 /* return "no privileges" instead of throwing an error */
3791 *is_missing = true;
3792 return 0;
3793 }
3794 else
3795 ereport(ERROR,
3796 (errcode(ERRCODE_UNDEFINED_OBJECT),
3797 errmsg("type with OID %u does not exist",
3798 rangetype)));
3799 }
3800 typeForm = (Form_pg_type) GETSTRUCT(tuple);
3801 }
3802
3803 /*
3804 * Now get the type's owner and ACL from the tuple
3805 */
3806 ownerId = typeForm->typowner;
3807
3808 aclDatum = SysCacheGetAttr(TYPEOID, tuple,
3809 Anum_pg_type_typacl, &isNull);
3810 if (isNull)
3811 {
3812 /* No ACL, so build default ACL */
3813 acl = acldefault(OBJECT_TYPE, ownerId);
3814 aclDatum = (Datum) 0;
3815 }
3816 else
3817 {
3818 /* detoast rel's ACL if necessary */
3819 acl = DatumGetAclP(aclDatum);
3820 }
3821
3822 result = aclmask(acl, roleid, ownerId, mask, how);
3823
3824 /* if we have a detoasted copy, free it */
3825 if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
3826 pfree(acl);
3827
3828 ReleaseSysCache(tuple);
3829
3830 return result;
3831 }
3832
3833 /*
3834 * Exported generic routine for checking a user's access privileges to an object
3835 */
3836 AclResult
3837 object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
3838 {
3839 return object_aclcheck_ext(classid, objectid, roleid, mode, NULL);
3840 }
3841
3842 /*
3843 * Exported generic routine for checking a user's access privileges to an
3844 * object, with is_missing
3845 */
3846 AclResult
3847 object_aclcheck_ext(Oid classid, Oid objectid,
3848 Oid roleid, AclMode mode,
3849 bool *is_missing)
3850 {
3851 if (object_aclmask_ext(classid, objectid, roleid, mode, ACLMASK_ANY,
3852 is_missing) != 0)
3853 return ACLCHECK_OK;
3854 else
3855 return ACLCHECK_NO_PRIV;
3856 }
3857
3858 /*
3859 * Exported routine for checking a user's access privileges to a column
3860 *
3861 * Returns ACLCHECK_OK if the user has any of the privileges identified by
3862 * 'mode'; otherwise returns a suitable error code (in practice, always
3863 * ACLCHECK_NO_PRIV).
3864 *
3865 * As with pg_attribute_aclmask, only privileges granted directly on the
3866 * column are considered here.
3867 */
3868 AclResult
3869 pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum,
3870 Oid roleid, AclMode mode)
3871 {
3872 return pg_attribute_aclcheck_ext(table_oid, attnum, roleid, mode, NULL);
3873 }
3874
3875
3876 /*
3877 * Exported routine for checking a user's access privileges to a column,
3878 * with is_missing
3879 */
3880 AclResult
3881 pg_attribute_aclcheck_ext(Oid table_oid, AttrNumber attnum,
3882 Oid roleid, AclMode mode, bool *is_missing)
3883 {
3884 if (pg_attribute_aclmask_ext(table_oid, attnum, roleid, mode,
3885 ACLMASK_ANY, is_missing) != 0)
3886 return ACLCHECK_OK;
3887 else
3888 return ACLCHECK_NO_PRIV;
3889 }
3890
3891 /*
3892 * Exported routine for checking a user's access privileges to any/all columns
3893 *
3894 * If 'how' is ACLMASK_ANY, then returns ACLCHECK_OK if user has any of the
3895 * privileges identified by 'mode' on any non-dropped column in the relation;
3896 * otherwise returns a suitable error code (in practice, always
3897 * ACLCHECK_NO_PRIV).
3898 *
3899 * If 'how' is ACLMASK_ALL, then returns ACLCHECK_OK if user has any of the
3900 * privileges identified by 'mode' on each non-dropped column in the relation
3901 * (and there must be at least one such column); otherwise returns a suitable
3902 * error code (in practice, always ACLCHECK_NO_PRIV).
3903 *
3904 * As with pg_attribute_aclmask, only privileges granted directly on the
3905 * column(s) are considered here.
3906 *
3907 * Note: system columns are not considered here; there are cases where that
3908 * might be appropriate but there are also cases where it wouldn't.
3909 */
3910 AclResult
3911 pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode,
3912 AclMaskHow how)
3913 {
3914 return pg_attribute_aclcheck_all_ext(table_oid, roleid, mode, how, NULL);
3915 }
3916
3917 /*
3918 * Exported routine for checking a user's access privileges to any/all columns,
3919 * with is_missing
3920 */
3921 AclResult
3922 pg_attribute_aclcheck_all_ext(Oid table_oid, Oid roleid,
3923 AclMode mode, AclMaskHow how,
3924 bool *is_missing)
3925 {
3926 AclResult result;
3927 HeapTuple classTuple;
3928 Form_pg_class classForm;
3929 Oid ownerId;
3930 AttrNumber nattrs;
3931 AttrNumber curr_att;
3932
3933 /*
3934 * Must fetch pg_class row to get owner ID and number of attributes.
3935 */
3936 classTuple = SearchSysCache1(RELOID, ObjectIdGetDatum(table_oid));
3937 if (!HeapTupleIsValid(classTuple))
3938 {
3939 if (is_missing != NULL)
3940 {
3941 /* return "no privileges" instead of throwing an error */
3942 *is_missing = true;
3943 return ACLCHECK_NO_PRIV;
3944 }
3945 else
3946 ereport(ERROR,
3947 (errcode(ERRCODE_UNDEFINED_TABLE),
3948 errmsg("relation with OID %u does not exist",
3949 table_oid)));
3950 }
3951 classForm = (Form_pg_class) GETSTRUCT(classTuple);
3952
3953 ownerId = classForm->relowner;
3954 nattrs = classForm->relnatts;
3955
3956 ReleaseSysCache(classTuple);
3957
3958 /*
3959 * Initialize result in case there are no non-dropped columns. We want to
3960 * report failure in such cases for either value of 'how'.
3961 */
3962 result = ACLCHECK_NO_PRIV;
3963
3964 for (curr_att = 1; curr_att <= nattrs; curr_att++)
3965 {
3966 HeapTuple attTuple;
3967 Datum aclDatum;
3968 bool isNull;
3969 Acl *acl;
3970 AclMode attmask;
3971
3972 attTuple = SearchSysCache2(ATTNUM,
3973 ObjectIdGetDatum(table_oid),
3974 Int16GetDatum(curr_att));
3975
3976 /*
3977 * Lookup failure probably indicates that the table was just dropped,
3978 * but we'll treat it the same as a dropped column rather than
3979 * throwing error.
3980 */
3981 if (!HeapTupleIsValid(attTuple))
3982 continue;
3983
3984 /* ignore dropped columns */
3985 if (((Form_pg_attribute) GETSTRUCT(attTuple))->attisdropped)
3986 {
3987 ReleaseSysCache(attTuple);
3988 continue;
3989 }
3990
3991 aclDatum = SysCacheGetAttr(ATTNUM, attTuple, Anum_pg_attribute_attacl,
3992 &isNull);
3993
3994 /*
3995 * Here we hard-wire knowledge that the default ACL for a column
3996 * grants no privileges, so that we can fall out quickly in the very
3997 * common case where attacl is null.
3998 */
3999 if (isNull)
4000 attmask = 0;
4001 else
4002 {
4003 /* detoast column's ACL if necessary */
4004 acl = DatumGetAclP(aclDatum);
4005
4006 attmask = aclmask(acl, roleid, ownerId, mode, ACLMASK_ANY);
4007
4008 /* if we have a detoasted copy, free it */
4009 if ((Pointer) acl != DatumGetPointer(aclDatum))
4010 pfree(acl);
4011 }
4012
4013 ReleaseSysCache(attTuple);
4014
4015 if (attmask != 0)
4016 {
4017 result = ACLCHECK_OK;
4018 if (how == ACLMASK_ANY)
4019 break; /* succeed on any success */
4020 }
4021 else
4022 {
4023 result = ACLCHECK_NO_PRIV;
4024 if (how == ACLMASK_ALL)
4025 break; /* fail on any failure */
4026 }
4027 }
4028
4029 return result;
4030 }
4031
4032 /*
4033 * Exported routine for checking a user's access privileges to a table
4034 *
4035 * Returns ACLCHECK_OK if the user has any of the privileges identified by
4036 * 'mode'; otherwise returns a suitable error code (in practice, always
4037 * ACLCHECK_NO_PRIV).
4038 */
4039 AclResult
4040 pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
4041 {
4042 return pg_class_aclcheck_ext(table_oid, roleid, mode, NULL);
4043 }
4044
4045 /*
4046 * Exported routine for checking a user's access privileges to a table,
4047 * with is_missing
4048 */
4049 AclResult
4050 pg_class_aclcheck_ext(Oid table_oid, Oid roleid,
4051 AclMode mode, bool *is_missing)
4052 {
4053 if (pg_class_aclmask_ext(table_oid, roleid, mode,
4054 ACLMASK_ANY, is_missing) != 0)
4055 return ACLCHECK_OK;
4056 else
4057 return ACLCHECK_NO_PRIV;
4058 }
4059
4060 /*
4061 * Exported routine for checking a user's access privileges to a configuration
4062 * parameter (GUC), identified by GUC name.
4063 */
4064 AclResult
4065 pg_parameter_aclcheck(const char *name, Oid roleid, AclMode mode)
4066 {
4067 if (pg_parameter_aclmask(name, roleid, mode, ACLMASK_ANY) != 0)
4068 return ACLCHECK_OK;
4069 else
4070 return ACLCHECK_NO_PRIV;
4071 }
4072
4073 /*
4074 * Exported routine for checking a user's access privileges to a largeobject
4075 */
4076 AclResult
4077 pg_largeobject_aclcheck_snapshot(Oid lobj_oid, Oid roleid, AclMode mode,
4078 Snapshot snapshot)
4079 {
4080 if (pg_largeobject_aclmask_snapshot(lobj_oid, roleid, mode,
4081 ACLMASK_ANY, snapshot) != 0)
4082 return ACLCHECK_OK;
4083 else
4084 return ACLCHECK_NO_PRIV;
4085 }
4086
4087 /*
4088 * Generic ownership check for an object
4089 */
4090 bool
4091 object_ownercheck(Oid classid, Oid objectid, Oid roleid)
4092 {
4093 int cacheid;
4094 Oid ownerId;
4095
4096 /* Superusers bypass all permission checking. */
4097 if (superuser_arg(roleid))
4098 return true;
4099
4100 /* For large objects, the catalog to consult is pg_largeobject_metadata */
4101 if (classid == LargeObjectRelationId)
4102 classid = LargeObjectMetadataRelationId;
4103
4104 cacheid = get_object_catcache_oid(classid);
4105 if (cacheid != -1)
4106 {
4107 /* we can get the object's tuple from the syscache */
4108 HeapTuple tuple;
4109
4110 tuple = SearchSysCache1(cacheid, ObjectIdGetDatum(objectid));
4111 if (!HeapTupleIsValid(tuple))
4112 elog(ERROR, "cache lookup failed for %s %u",
4113 get_object_class_descr(classid), objectid);
4114
4115 ownerId = DatumGetObjectId(SysCacheGetAttrNotNull(cacheid,
4116 tuple,
4117 get_object_attnum_owner(classid)));
4118 ReleaseSysCache(tuple);
4119 }
4120 else
4121 {
4122 /* for catalogs without an appropriate syscache */
4123 Relation rel;
4124 ScanKeyData entry[1];
4125 SysScanDesc scan;
4126 HeapTuple tuple;
4127 bool isnull;
4128
4129 rel = table_open(classid, AccessShareLock);
4130
4131 ScanKeyInit(&entry[0],
4132 get_object_attnum_oid(classid),
4133 BTEqualStrategyNumber, F_OIDEQ,
4134 ObjectIdGetDatum(objectid));
4135
4136 scan = systable_beginscan(rel,
4137 get_object_oid_index(classid), true,
4138 NULL, 1, entry);
4139
4140 tuple = systable_getnext(scan);
4141 if (!HeapTupleIsValid(tuple))
4142 elog(ERROR, "could not find tuple for %s %u",
4143 get_object_class_descr(classid), objectid);
4144
4145 ownerId = DatumGetObjectId(heap_getattr(tuple,
4146 get_object_attnum_owner(classid),
4147 RelationGetDescr(rel),
4148 &isnull));
4149 Assert(!isnull);
4150
4151 systable_endscan(scan);
4152 table_close(rel, AccessShareLock);
4153 }
4154
4155 return has_privs_of_role(roleid, ownerId);
4156 }
4157
4158 /*
4159 * Check whether specified role has CREATEROLE privilege (or is a superuser)
4160 *
4161 * Note: roles do not have owners per se; instead we use this test in
4162 * places where an ownership-like permissions test is needed for a role.
4163 * Be sure to apply it to the role trying to do the operation, not the
4164 * role being operated on! Also note that this generally should not be
4165 * considered enough privilege if the target role is a superuser.
4166 * (We don't handle that consideration here because we want to give a
4167 * separate error message for such cases, so the caller has to deal with it.)
4168 */
4169 bool
4170 has_createrole_privilege(Oid roleid)
4171 {
4172 bool result = false;
4173 HeapTuple utup;
4174
4175 /* Superusers bypass all permission checking. */
4176 if (superuser_arg(roleid))
4177 return true;
4178
4179 utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
4180 if (HeapTupleIsValid(utup))
4181 {
4182 result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreaterole;
4183 ReleaseSysCache(utup);
4184 }
4185 return result;
4186 }
4187
4188 bool
4189 has_bypassrls_privilege(Oid roleid)
4190 {
4191 bool result = false;
4192 HeapTuple utup;
4193
4194 /* Superusers bypass all permission checking. */
4195 if (superuser_arg(roleid))
4196 return true;
4197
4198 utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
4199 if (HeapTupleIsValid(utup))
4200 {
4201 result = ((Form_pg_authid) GETSTRUCT(utup))->rolbypassrls;
4202 ReleaseSysCache(utup);
4203 }
4204 return result;
4205 }
4206
4207 /*
4208 * Fetch pg_default_acl entry for given role, namespace and object type
4209 * (object type must be given in pg_default_acl's encoding).
4210 * Returns NULL if no such entry.
4211 */
4212 static Acl *
4213 get_default_acl_internal(Oid roleId, Oid nsp_oid, char objtype)
4214 {
4215 Acl *result = NULL;
4216 HeapTuple tuple;
4217
4218 tuple = SearchSysCache3(DEFACLROLENSPOBJ,
4219 ObjectIdGetDatum(roleId),
4220 ObjectIdGetDatum(nsp_oid),
4221 CharGetDatum(objtype));
4222
4223 if (HeapTupleIsValid(tuple))
4224 {
4225 Datum aclDatum;
4226 bool isNull;
4227
4228 aclDatum = SysCacheGetAttr(DEFACLROLENSPOBJ, tuple,
4229 Anum_pg_default_acl_defaclacl,
4230 &isNull);
4231 if (!isNull)
4232 result = DatumGetAclPCopy(aclDatum);
4233 ReleaseSysCache(tuple);
4234 }
4235
4236 return result;
4237 }
4238
4239 /*
4240 * Get default permissions for newly created object within given schema
4241 *
4242 * Returns NULL if built-in system defaults should be used.
4243 *
4244 * If the result is not NULL, caller must call recordDependencyOnNewAcl
4245 * once the OID of the new object is known.
4246 */
4247 Acl *
4248 get_user_default_acl(ObjectType objtype, Oid ownerId, Oid nsp_oid)
4249 {
4250 Acl *result;
4251 Acl *glob_acl;
4252 Acl *schema_acl;
4253 Acl *def_acl;
4254 char defaclobjtype;
4255
4256 /*
4257 * Use NULL during bootstrap, since pg_default_acl probably isn't there
4258 * yet.
4259 */
4260 if (IsBootstrapProcessingMode())
4261 return NULL;
4262
4263 /* Check if object type is supported in pg_default_acl */
4264 switch (objtype)
4265 {
4266 case OBJECT_TABLE:
4267 defaclobjtype = DEFACLOBJ_RELATION;
4268 break;
4269
4270 case OBJECT_SEQUENCE:
4271 defaclobjtype = DEFACLOBJ_SEQUENCE;
4272 break;
4273
4274 case OBJECT_FUNCTION:
4275 defaclobjtype = DEFACLOBJ_FUNCTION;
4276 break;
4277
4278 case OBJECT_TYPE:
4279 defaclobjtype = DEFACLOBJ_TYPE;
4280 break;
4281
4282 case OBJECT_SCHEMA:
4283 defaclobjtype = DEFACLOBJ_NAMESPACE;
4284 break;
4285
4286 case OBJECT_LARGEOBJECT:
4287 defaclobjtype = DEFACLOBJ_LARGEOBJECT;
4288 break;
4289
4290 default:
4291 return NULL;
4292 }
4293
4294 /* Look up the relevant pg_default_acl entries */
4295 glob_acl = get_default_acl_internal(ownerId, InvalidOid, defaclobjtype);
4296 schema_acl = get_default_acl_internal(ownerId, nsp_oid, defaclobjtype);
4297
4298 /* Quick out if neither entry exists */
4299 if (glob_acl == NULL && schema_acl == NULL)
4300 return NULL;
4301
4302 /* We need to know the hard-wired default value, too */
4303 def_acl = acldefault(objtype, ownerId);
4304
4305 /* If there's no global entry, substitute the hard-wired default */
4306 if (glob_acl == NULL)
4307 glob_acl = def_acl;
4308
4309 /* Merge in any per-schema privileges */
4310 result = aclmerge(glob_acl, schema_acl, ownerId);
4311
4312 /*
4313 * For efficiency, we want to return NULL if the result equals default.
4314 * This requires sorting both arrays to get an accurate comparison.
4315 */
4316 aclitemsort(result);
4317 aclitemsort(def_acl);
4318 if (aclequal(result, def_acl))
4319 result = NULL;
4320
4321 return result;
4322 }
4323
4324 /*
4325 * Record dependencies on roles mentioned in a new object's ACL.
4326 */
4327 void
4328 recordDependencyOnNewAcl(Oid classId, Oid objectId, int32 objsubId,
4329 Oid ownerId, Acl *acl)
4330 {
4331 int nmembers;
4332 Oid *members;
4333
4334 /* Nothing to do if ACL is defaulted */
4335 if (acl == NULL)
4336 return;
4337
4338 /* Extract roles mentioned in ACL */
4339 nmembers = aclmembers(acl, &members);
4340
4341 /* Update the shared dependency ACL info */
4342 updateAclDependencies(classId, objectId, objsubId,
4343 ownerId,
4344 0, NULL,
4345 nmembers, members);
4346 }
4347
4348 /*
4349 * Record initial privileges for the top-level object passed in.
4350 *
4351 * For the object passed in, this will record its ACL (if any) and the ACLs of
4352 * any sub-objects (eg: columns) into pg_init_privs.
4353 */
4354 void
4355 recordExtObjInitPriv(Oid objoid, Oid classoid)
4356 {
4357 /*
4358 * pg_class / pg_attribute
4359 *
4360 * If this is a relation then we need to see if there are any sub-objects
4361 * (eg: columns) for it and, if so, be sure to call
4362 * recordExtensionInitPrivWorker() for each one.
4363 */
4364 if (classoid == RelationRelationId)
4365 {
4366 Form_pg_class pg_class_tuple;
4367 Datum aclDatum;
4368 bool isNull;
4369 HeapTuple tuple;
4370
4371 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(objoid));
4372 if (!HeapTupleIsValid(tuple))
4373 elog(ERROR, "cache lookup failed for relation %u", objoid);
4374 pg_class_tuple = (Form_pg_class) GETSTRUCT(tuple);
4375
4376 /*
4377 * Indexes don't have permissions, neither do the pg_class rows for
4378 * composite types. (These cases are unreachable given the
4379 * restrictions in ALTER EXTENSION ADD, but let's check anyway.)
4380 */
4381 if (pg_class_tuple->relkind == RELKIND_INDEX ||
4382 pg_class_tuple->relkind == RELKIND_PARTITIONED_INDEX ||
4383 pg_class_tuple->relkind == RELKIND_COMPOSITE_TYPE)
4384 {
4385 ReleaseSysCache(tuple);
4386 return;
4387 }
4388
4389 /*
4390 * If this isn't a sequence then it's possibly going to have
4391 * column-level ACLs associated with it.
4392 */
4393 if (pg_class_tuple->relkind != RELKIND_SEQUENCE)
4394 {
4395 AttrNumber curr_att;
4396 AttrNumber nattrs = pg_class_tuple->relnatts;
4397
4398 for (curr_att = 1; curr_att <= nattrs; curr_att++)
4399 {
4400 HeapTuple attTuple;
4401 Datum attaclDatum;
4402
4403 attTuple = SearchSysCache2(ATTNUM,
4404 ObjectIdGetDatum(objoid),
4405 Int16GetDatum(curr_att));
4406
4407 if (!HeapTupleIsValid(attTuple))
4408 continue;
4409
4410 /* ignore dropped columns */
4411 if (((Form_pg_attribute) GETSTRUCT(attTuple))->attisdropped)
4412 {
4413 ReleaseSysCache(attTuple);
4414 continue;
4415 }
4416
4417 attaclDatum = SysCacheGetAttr(ATTNUM, attTuple,
4418 Anum_pg_attribute_attacl,
4419 &isNull);
4420
4421 /* no need to do anything for a NULL ACL */
4422 if (isNull)
4423 {
4424 ReleaseSysCache(attTuple);
4425 continue;
4426 }
4427
4428 recordExtensionInitPrivWorker(objoid, classoid, curr_att,
4429 DatumGetAclP(attaclDatum));
4430
4431 ReleaseSysCache(attTuple);
4432 }
4433 }
4434
4435 aclDatum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relacl,
4436 &isNull);
4437
4438 /* Add the record, if any, for the top-level object */
4439 if (!isNull)
4440 recordExtensionInitPrivWorker(objoid, classoid, 0,
4441 DatumGetAclP(aclDatum));
4442
4443 ReleaseSysCache(tuple);
4444 }
4445 else if (classoid == LargeObjectRelationId)
4446 {
4447 /* For large objects, we must consult pg_largeobject_metadata */
4448 Datum aclDatum;
4449 bool isNull;
4450 HeapTuple tuple;
4451 ScanKeyData entry[1];
4452 SysScanDesc scan;
4453 Relation relation;
4454
4455 /*
4456 * Note: this is dead code, given that we don't allow large objects to
4457 * be made extension members. But it seems worth carrying in case
4458 * some future caller of this function has need for it.
4459 */
4460 relation = table_open(LargeObjectMetadataRelationId, RowExclusiveLock);
4461
4462 /* There's no syscache for pg_largeobject_metadata */
4463 ScanKeyInit(&entry[0],
4464 Anum_pg_largeobject_metadata_oid,
4465 BTEqualStrategyNumber, F_OIDEQ,
4466 ObjectIdGetDatum(objoid));
4467
4468 scan = systable_beginscan(relation,
4469 LargeObjectMetadataOidIndexId, true,
4470 NULL, 1, entry);
4471
4472 tuple = systable_getnext(scan);
4473 if (!HeapTupleIsValid(tuple))
4474 elog(ERROR, "could not find tuple for large object %u", objoid);
4475
4476 aclDatum = heap_getattr(tuple,
4477 Anum_pg_largeobject_metadata_lomacl,
4478 RelationGetDescr(relation), &isNull);
4479
4480 /* Add the record, if any, for the top-level object */
4481 if (!isNull)
4482 recordExtensionInitPrivWorker(objoid, classoid, 0,
4483 DatumGetAclP(aclDatum));
4484
4485 systable_endscan(scan);
4486 }
4487 /* This will error on unsupported classoid. */
4488 else if (get_object_attnum_acl(classoid) != InvalidAttrNumber)
4489 {
4490 int cacheid;
4491 Datum aclDatum;
4492 bool isNull;
4493 HeapTuple tuple;
4494
4495 cacheid = get_object_catcache_oid(classoid);
4496 tuple = SearchSysCache1(cacheid, ObjectIdGetDatum(objoid));
4497 if (!HeapTupleIsValid(tuple))
4498 elog(ERROR, "cache lookup failed for %s %u",
4499 get_object_class_descr(classoid), objoid);
4500
4501 aclDatum = SysCacheGetAttr(cacheid, tuple,
4502 get_object_attnum_acl(classoid),
4503 &isNull);
4504
4505 /* Add the record, if any, for the top-level object */
4506 if (!isNull)
4507 recordExtensionInitPrivWorker(objoid, classoid, 0,
4508 DatumGetAclP(aclDatum));
4509
4510 ReleaseSysCache(tuple);
4511 }
4512 }
4513
4514 /*
4515 * For the object passed in, remove its ACL and the ACLs of any object subIds
4516 * from pg_init_privs (via recordExtensionInitPrivWorker()).
4517 */
4518 void
4519 removeExtObjInitPriv(Oid objoid, Oid classoid)
4520 {
4521 /*
4522 * If this is a relation then we need to see if there are any sub-objects
4523 * (eg: columns) for it and, if so, be sure to call
4524 * recordExtensionInitPrivWorker() for each one.
4525 */
4526 if (classoid == RelationRelationId)
4527 {
4528 Form_pg_class pg_class_tuple;
4529 HeapTuple tuple;
4530
4531 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(objoid));
4532 if (!HeapTupleIsValid(tuple))
4533 elog(ERROR, "cache lookup failed for relation %u", objoid);
4534 pg_class_tuple = (Form_pg_class) GETSTRUCT(tuple);
4535
4536 /*
4537 * Indexes don't have permissions, neither do the pg_class rows for
4538 * composite types. (These cases are unreachable given the
4539 * restrictions in ALTER EXTENSION DROP, but let's check anyway.)
4540 */
4541 if (pg_class_tuple->relkind == RELKIND_INDEX ||
4542 pg_class_tuple->relkind == RELKIND_PARTITIONED_INDEX ||
4543 pg_class_tuple->relkind == RELKIND_COMPOSITE_TYPE)
4544 {
4545 ReleaseSysCache(tuple);
4546 return;
4547 }
4548
4549 /*
4550 * If this isn't a sequence then it's possibly going to have
4551 * column-level ACLs associated with it.
4552 */
4553 if (pg_class_tuple->relkind != RELKIND_SEQUENCE)
4554 {
4555 AttrNumber curr_att;
4556 AttrNumber nattrs = pg_class_tuple->relnatts;
4557
4558 for (curr_att = 1; curr_att <= nattrs; curr_att++)
4559 {
4560 HeapTuple attTuple;
4561
4562 attTuple = SearchSysCache2(ATTNUM,
4563 ObjectIdGetDatum(objoid),
4564 Int16GetDatum(curr_att));
4565
4566 if (!HeapTupleIsValid(attTuple))
4567 continue;
4568
4569 /* when removing, remove all entries, even dropped columns */
4570
4571 recordExtensionInitPrivWorker(objoid, classoid, curr_att, NULL);
4572
4573 ReleaseSysCache(attTuple);
4574 }
4575 }
4576
4577 ReleaseSysCache(tuple);
4578 }
4579
4580 /* Remove the record, if any, for the top-level object */
4581 recordExtensionInitPrivWorker(objoid, classoid, 0, NULL);
4582 }
4583
4584 /*
4585 * Record initial ACL for an extension object
4586 *
4587 * Can be called at any time, we check if 'creating_extension' is set and, if
4588 * not, exit immediately.
4589 *
4590 * Pass in the object OID, the OID of the class (the OID of the table which
4591 * the object is defined in) and the 'sub' id of the object (objsubid), if
4592 * any. If there is no 'sub' id (they are currently only used for columns of
4593 * tables) then pass in '0'. Finally, pass in the complete ACL to store.
4594 *
4595 * If an ACL already exists for this object/sub-object then we will replace
4596 * it with what is passed in.
4597 *
4598 * Passing in NULL for 'new_acl' will result in the entry for the object being
4599 * removed, if one is found.
4600 */
4601 static void
4602 recordExtensionInitPriv(Oid objoid, Oid classoid, int objsubid, Acl *new_acl)
4603 {
4604 /*
4605 * Generally, we only record the initial privileges when an extension is
4606 * being created, but because we don't actually use CREATE EXTENSION
4607 * during binary upgrades with pg_upgrade, there is a variable to let us
4608 * know that the GRANT and REVOKE statements being issued, while this
4609 * variable is true, are for the initial privileges of the extension
4610 * object and therefore we need to record them.
4611 */
4612 if (!creating_extension && !binary_upgrade_record_init_privs)
4613 return;
4614
4615 recordExtensionInitPrivWorker(objoid, classoid, objsubid, new_acl);
4616 }
4617
4618 /*
4619 * Record initial ACL for an extension object, worker.
4620 *
4621 * This will perform a wholesale replacement of the entire ACL for the object
4622 * passed in, therefore be sure to pass in the complete new ACL to use.
4623 *
4624 * Generally speaking, do *not* use this function directly but instead use
4625 * recordExtensionInitPriv(), which checks if 'creating_extension' is set.
4626 * This function does *not* check if 'creating_extension' is set as it is also
4627 * used when an object is added to or removed from an extension via ALTER
4628 * EXTENSION ... ADD/DROP.
4629 */
4630 static void
4631 recordExtensionInitPrivWorker(Oid objoid, Oid classoid, int objsubid,
4632 Acl *new_acl)
4633 {
4634 Relation relation;
4635 ScanKeyData key[3];
4636 SysScanDesc scan;
4637 HeapTuple tuple;
4638 HeapTuple oldtuple;
4639 int noldmembers;
4640 int nnewmembers;
4641 Oid *oldmembers;
4642 Oid *newmembers;
4643
4644 /* We'll need the role membership of the new ACL. */
4645 nnewmembers = aclmembers(new_acl, &newmembers);
4646
4647 /* Search pg_init_privs for an existing entry. */
4648 relation = table_open(InitPrivsRelationId, RowExclusiveLock);
4649
4650 ScanKeyInit(&key[0],
4651 Anum_pg_init_privs_objoid,
4652 BTEqualStrategyNumber, F_OIDEQ,
4653 ObjectIdGetDatum(objoid));
4654 ScanKeyInit(&key[1],
4655 Anum_pg_init_privs_classoid,
4656 BTEqualStrategyNumber, F_OIDEQ,
4657 ObjectIdGetDatum(classoid));
4658 ScanKeyInit(&key[2],
4659 Anum_pg_init_privs_objsubid,
4660 BTEqualStrategyNumber, F_INT4EQ,
4661 Int32GetDatum(objsubid));
4662
4663 scan = systable_beginscan(relation, InitPrivsObjIndexId, true,
4664 NULL, 3, key);
4665
4666 /* There should exist only one entry or none. */
4667 oldtuple = systable_getnext(scan);
4668
4669 /* If we find an entry, update it with the latest ACL. */
4670 if (HeapTupleIsValid(oldtuple))
4671 {
4672 Datum values[Natts_pg_init_privs] = {0};
4673 bool nulls[Natts_pg_init_privs] = {0};
4674 bool replace[Natts_pg_init_privs] = {0};
4675 Datum oldAclDatum;
4676 bool isNull;
4677 Acl *old_acl;
4678
4679 /* Update pg_shdepend for roles mentioned in the old/new ACLs. */
4680 oldAclDatum = heap_getattr(oldtuple, Anum_pg_init_privs_initprivs,
4681 RelationGetDescr(relation), &isNull);
4682 Assert(!isNull);
4683 old_acl = DatumGetAclP(oldAclDatum);
4684 noldmembers = aclmembers(old_acl, &oldmembers);
4685
4686 updateInitAclDependencies(classoid, objoid, objsubid,
4687 noldmembers, oldmembers,
4688 nnewmembers, newmembers);
4689
4690 /* If we have a new ACL to set, then update the row with it. */
4691 if (new_acl && ACL_NUM(new_acl) != 0)
4692 {
4693 values[Anum_pg_init_privs_initprivs - 1] = PointerGetDatum(new_acl);
4694 replace[Anum_pg_init_privs_initprivs - 1] = true;
4695
4696 oldtuple = heap_modify_tuple(oldtuple, RelationGetDescr(relation),
4697 values, nulls, replace);
4698
4699 CatalogTupleUpdate(relation, &oldtuple->t_self, oldtuple);
4700 }
4701 else
4702 {
4703 /* new_acl is NULL/empty, so delete the entry we found. */
4704 CatalogTupleDelete(relation, &oldtuple->t_self);
4705 }
4706 }
4707 else
4708 {
4709 Datum values[Natts_pg_init_privs] = {0};
4710 bool nulls[Natts_pg_init_privs] = {0};
4711
4712 /*
4713 * Only add a new entry if the new ACL is non-NULL.
4714 *
4715 * If we are passed in a NULL ACL and no entry exists, we can just
4716 * fall through and do nothing.
4717 */
4718 if (new_acl && ACL_NUM(new_acl) != 0)
4719 {
4720 /* No entry found, so add it. */
4721 values[Anum_pg_init_privs_objoid - 1] = ObjectIdGetDatum(objoid);
4722 values[Anum_pg_init_privs_classoid - 1] = ObjectIdGetDatum(classoid);
4723 values[Anum_pg_init_privs_objsubid - 1] = Int32GetDatum(objsubid);
4724
4725 /* This function only handles initial privileges of extensions */
4726 values[Anum_pg_init_privs_privtype - 1] =
4727 CharGetDatum(INITPRIVS_EXTENSION);
4728
4729 values[Anum_pg_init_privs_initprivs - 1] = PointerGetDatum(new_acl);
4730
4731 tuple = heap_form_tuple(RelationGetDescr(relation), values, nulls);
4732
4733 CatalogTupleInsert(relation, tuple);
4734
4735 /* Update pg_shdepend, too. */
4736 noldmembers = 0;
4737 oldmembers = NULL;
4738
4739 updateInitAclDependencies(classoid, objoid, objsubid,
4740 noldmembers, oldmembers,
4741 nnewmembers, newmembers);
4742 }
4743 }
4744
4745 systable_endscan(scan);
4746
4747 /* prevent error when processing objects multiple times */
4748 CommandCounterIncrement();
4749
4750 table_close(relation, RowExclusiveLock);
4751 }
4752
4753 /*
4754 * ReplaceRoleInInitPriv
4755 *
4756 * Used by shdepReassignOwned to replace mentions of a role in pg_init_privs.
4757 */
4758 void
4759 ReplaceRoleInInitPriv(Oid oldroleid, Oid newroleid,
4760 Oid classid, Oid objid, int32 objsubid)
4761 {
4762 Relation rel;
4763 ScanKeyData key[3];
4764 SysScanDesc scan;
4765 HeapTuple oldtuple;
4766 Datum oldAclDatum;
4767 bool isNull;
4768 Acl *old_acl;
4769 Acl *new_acl;
4770 HeapTuple newtuple;
4771 int noldmembers;
4772 int nnewmembers;
4773 Oid *oldmembers;
4774 Oid *newmembers;
4775
4776 /* Search for existing pg_init_privs entry for the target object. */
4777 rel = table_open(InitPrivsRelationId, RowExclusiveLock);
4778
4779 ScanKeyInit(&key[0],
4780 Anum_pg_init_privs_objoid,
4781 BTEqualStrategyNumber, F_OIDEQ,
4782 ObjectIdGetDatum(objid));
4783 ScanKeyInit(&key[1],
4784 Anum_pg_init_privs_classoid,
4785 BTEqualStrategyNumber, F_OIDEQ,
4786 ObjectIdGetDatum(classid));
4787 ScanKeyInit(&key[2],
4788 Anum_pg_init_privs_objsubid,
4789 BTEqualStrategyNumber, F_INT4EQ,
4790 Int32GetDatum(objsubid));
4791
4792 scan = systable_beginscan(rel, InitPrivsObjIndexId, true,
4793 NULL, 3, key);
4794
4795 /* There should exist only one entry or none. */
4796 oldtuple = systable_getnext(scan);
4797
4798 if (!HeapTupleIsValid(oldtuple))
4799 {
4800 /*
4801 * Hmm, why are we here if there's no entry? But pack up and go away
4802 * quietly.
4803 */
4804 systable_endscan(scan);
4805 table_close(rel, RowExclusiveLock);
4806 return;
4807 }
4808
4809 /* Get a writable copy of the existing ACL. */
4810 oldAclDatum = heap_getattr(oldtuple, Anum_pg_init_privs_initprivs,
4811 RelationGetDescr(rel), &isNull);
4812 Assert(!isNull);
4813 old_acl = DatumGetAclPCopy(oldAclDatum);
4814
4815 /*
4816 * Generate new ACL. This usage of aclnewowner is a bit off-label when
4817 * oldroleid isn't the owner; but it does the job fine.
4818 */
4819 new_acl = aclnewowner(old_acl, oldroleid, newroleid);
4820
4821 /*
4822 * If we end with an empty ACL, delete the pg_init_privs entry. (That
4823 * probably can't happen here, but we may as well cover the case.)
4824 */
4825 if (new_acl == NULL || ACL_NUM(new_acl) == 0)
4826 {
4827 CatalogTupleDelete(rel, &oldtuple->t_self);
4828 }
4829 else
4830 {
4831 Datum values[Natts_pg_init_privs] = {0};
4832 bool nulls[Natts_pg_init_privs] = {0};
4833 bool replaces[Natts_pg_init_privs] = {0};
4834
4835 /* Update existing entry. */
4836 values[Anum_pg_init_privs_initprivs - 1] = PointerGetDatum(new_acl);
4837 replaces[Anum_pg_init_privs_initprivs - 1] = true;
4838
4839 newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(rel),
4840 values, nulls, replaces);
4841 CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
4842 }
4843
4844 /*
4845 * Update the shared dependency ACL info.
4846 */
4847 noldmembers = aclmembers(old_acl, &oldmembers);
4848 nnewmembers = aclmembers(new_acl, &newmembers);
4849
4850 updateInitAclDependencies(classid, objid, objsubid,
4851 noldmembers, oldmembers,
4852 nnewmembers, newmembers);
4853
4854 systable_endscan(scan);
4855
4856 /* prevent error when processing objects multiple times */
4857 CommandCounterIncrement();
4858
4859 table_close(rel, RowExclusiveLock);
4860 }
4861
4862 /*
4863 * RemoveRoleFromInitPriv
4864 *
4865 * Used by shdepDropOwned to remove mentions of a role in pg_init_privs.
4866 */
4867 void
4868 RemoveRoleFromInitPriv(Oid roleid, Oid classid, Oid objid, int32 objsubid)
4869 {
4870 Relation rel;
4871 ScanKeyData key[3];
4872 SysScanDesc scan;
4873 HeapTuple oldtuple;
4874 int cacheid;
4875 HeapTuple objtuple;
4876 Oid ownerId;
4877 Datum oldAclDatum;
4878 bool isNull;
4879 Acl *old_acl;
4880 Acl *new_acl;
4881 HeapTuple newtuple;
4882 int noldmembers;
4883 int nnewmembers;
4884 Oid *oldmembers;
4885 Oid *newmembers;
4886
4887 /* Search for existing pg_init_privs entry for the target object. */
4888 rel = table_open(InitPrivsRelationId, RowExclusiveLock);
4889
4890 ScanKeyInit(&key[0],
4891 Anum_pg_init_privs_objoid,
4892 BTEqualStrategyNumber, F_OIDEQ,
4893 ObjectIdGetDatum(objid));
4894 ScanKeyInit(&key[1],
4895 Anum_pg_init_privs_classoid,
4896 BTEqualStrategyNumber, F_OIDEQ,
4897 ObjectIdGetDatum(classid));
4898 ScanKeyInit(&key[2],
4899 Anum_pg_init_privs_objsubid,
4900 BTEqualStrategyNumber, F_INT4EQ,
4901 Int32GetDatum(objsubid));
4902
4903 scan = systable_beginscan(rel, InitPrivsObjIndexId, true,
4904 NULL, 3, key);
4905
4906 /* There should exist only one entry or none. */
4907 oldtuple = systable_getnext(scan);
4908
4909 if (!HeapTupleIsValid(oldtuple))
4910 {
4911 /*
4912 * Hmm, why are we here if there's no entry? But pack up and go away
4913 * quietly.
4914 */
4915 systable_endscan(scan);
4916 table_close(rel, RowExclusiveLock);
4917 return;
4918 }
4919
4920 /* Get a writable copy of the existing ACL. */
4921 oldAclDatum = heap_getattr(oldtuple, Anum_pg_init_privs_initprivs,
4922 RelationGetDescr(rel), &isNull);
4923 Assert(!isNull);
4924 old_acl = DatumGetAclPCopy(oldAclDatum);
4925
4926 /*
4927 * We need the members of both old and new ACLs so we can correct the
4928 * shared dependency information. Collect data before
4929 * merge_acl_with_grant throws away old_acl.
4930 */
4931 noldmembers = aclmembers(old_acl, &oldmembers);
4932
4933 /* Must find out the owner's OID the hard way. */
4934 cacheid = get_object_catcache_oid(classid);
4935 objtuple = SearchSysCache1(cacheid, ObjectIdGetDatum(objid));
4936 if (!HeapTupleIsValid(objtuple))
4937 elog(ERROR, "cache lookup failed for %s %u",
4938 get_object_class_descr(classid), objid);
4939
4940 ownerId = DatumGetObjectId(SysCacheGetAttrNotNull(cacheid,
4941 objtuple,
4942 get_object_attnum_owner(classid)));
4943 ReleaseSysCache(objtuple);
4944
4945 /*
4946 * Generate new ACL. Grantor of rights is always the same as the owner.
4947 */
4948 if (old_acl != NULL)
4949 new_acl = merge_acl_with_grant(old_acl,
4950 false, /* is_grant */
4951 false, /* grant_option */
4952 DROP_RESTRICT,
4953 list_make1_oid(roleid),
4954 ACLITEM_ALL_PRIV_BITS,
4955 ownerId,
4956 ownerId);
4957 else
4958 new_acl = NULL; /* this case shouldn't happen, probably */
4959
4960 /* If we end with an empty ACL, delete the pg_init_privs entry. */
4961 if (new_acl == NULL || ACL_NUM(new_acl) == 0)
4962 {
4963 CatalogTupleDelete(rel, &oldtuple->t_self);
4964 }
4965 else
4966 {
4967 Datum values[Natts_pg_init_privs] = {0};
4968 bool nulls[Natts_pg_init_privs] = {0};
4969 bool replaces[Natts_pg_init_privs] = {0};
4970
4971 /* Update existing entry. */
4972 values[Anum_pg_init_privs_initprivs - 1] = PointerGetDatum(new_acl);
4973 replaces[Anum_pg_init_privs_initprivs - 1] = true;
4974
4975 newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(rel),
4976 values, nulls, replaces);
4977 CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
4978 }
4979
4980 /*
4981 * Update the shared dependency ACL info.
4982 */
4983 nnewmembers = aclmembers(new_acl, &newmembers);
4984
4985 updateInitAclDependencies(classid, objid, objsubid,
4986 noldmembers, oldmembers,
4987 nnewmembers, newmembers);
4988
4989 systable_endscan(scan);
4990
4991 /* prevent error when processing objects multiple times */
4992 CommandCounterIncrement();
4993
4994 table_close(rel, RowExclusiveLock);
4995 }