Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * policy.c
4 : : * Commands for manipulating policies.
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : * src/backend/commands/policy.c
10 : : *
11 : : *-------------------------------------------------------------------------
12 : : */
13 : : #include "postgres.h"
14 : :
15 : : #include "access/genam.h"
16 : : #include "access/htup.h"
17 : : #include "access/htup_details.h"
18 : : #include "access/relation.h"
19 : : #include "access/table.h"
20 : : #include "access/xact.h"
21 : : #include "catalog/catalog.h"
22 : : #include "catalog/dependency.h"
23 : : #include "catalog/indexing.h"
24 : : #include "catalog/namespace.h"
25 : : #include "catalog/objectaccess.h"
26 : : #include "catalog/pg_authid.h"
27 : : #include "catalog/pg_policy.h"
28 : : #include "catalog/pg_type.h"
29 : : #include "commands/policy.h"
30 : : #include "miscadmin.h"
31 : : #include "nodes/pg_list.h"
32 : : #include "parser/parse_clause.h"
33 : : #include "parser/parse_collate.h"
34 : : #include "parser/parse_node.h"
35 : : #include "parser/parse_relation.h"
36 : : #include "rewrite/rewriteManip.h"
37 : : #include "rewrite/rowsecurity.h"
38 : : #include "utils/acl.h"
39 : : #include "utils/array.h"
40 : : #include "utils/builtins.h"
41 : : #include "utils/fmgroids.h"
42 : : #include "utils/inval.h"
43 : : #include "utils/lsyscache.h"
44 : : #include "utils/memutils.h"
45 : : #include "utils/rel.h"
46 : : #include "utils/syscache.h"
47 : :
48 : : static void RangeVarCallbackForPolicy(const RangeVar *rv,
49 : : Oid relid, Oid oldrelid, void *arg);
50 : : static char parse_policy_command(const char *cmd_name);
51 : : static Datum *policy_role_list_to_array(List *roles, int *num_roles);
52 : :
53 : : /*
54 : : * Callback to RangeVarGetRelidExtended().
55 : : *
56 : : * Checks the following:
57 : : * - the relation specified is a table.
58 : : * - current user owns the table.
59 : : * - the table is not a system table.
60 : : *
61 : : * If any of these checks fails then an error is raised.
62 : : */
63 : : static void
64 : 654 : RangeVarCallbackForPolicy(const RangeVar *rv, Oid relid, Oid oldrelid,
65 : : void *arg)
66 : : {
67 : : HeapTuple tuple;
68 : : Form_pg_class classform;
69 : : char relkind;
70 : :
71 : 654 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
72 [ - + ]: 654 : if (!HeapTupleIsValid(tuple))
73 : 0 : return;
74 : :
75 : 654 : classform = (Form_pg_class) GETSTRUCT(tuple);
76 : 654 : relkind = classform->relkind;
77 : :
78 : : /* Must own relation. */
79 [ + + ]: 654 : if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
80 : 8 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
81 : :
82 : : /*
83 : : * Conflict log tables are used internally for logical replication
84 : : * conflict logging and should not be modified directly, as it could
85 : : * disrupt conflict logging.
86 : : */
87 [ + + ]: 646 : if (IsConflictLogTableClass(classform))
88 [ + - ]: 4 : ereport(ERROR,
89 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
90 : : errmsg("cannot create policy on conflict log table \"%s\"",
91 : : rv->relname),
92 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
93 : :
94 : : /* No system table modifications unless explicitly allowed. */
95 [ + + + + ]: 642 : if (!allowSystemTableMods && IsSystemClass(relid, classform))
96 [ + - ]: 1 : ereport(ERROR,
97 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
98 : : errmsg("permission denied: \"%s\" is a system catalog",
99 : : rv->relname)));
100 : :
101 : : /* Relation type MUST be a table. */
102 [ + + - + ]: 641 : if (relkind != RELKIND_RELATION && relkind != RELKIND_PARTITIONED_TABLE)
103 [ # # ]: 0 : ereport(ERROR,
104 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
105 : : errmsg("\"%s\" is not a table", rv->relname)));
106 : :
107 : 641 : ReleaseSysCache(tuple);
108 : : }
109 : :
110 : : /*
111 : : * parse_policy_command -
112 : : * helper function to convert full command strings to their char
113 : : * representation.
114 : : *
115 : : * cmd_name - full string command name. Valid values are 'all', 'select',
116 : : * 'insert', 'update' and 'delete'.
117 : : *
118 : : */
119 : : static char
120 : 547 : parse_policy_command(const char *cmd_name)
121 : : {
122 : : char polcmd;
123 : :
124 [ - + ]: 547 : if (!cmd_name)
125 [ # # ]: 0 : elog(ERROR, "unrecognized policy command");
126 : :
127 [ + + ]: 547 : if (strcmp(cmd_name, "all") == 0)
128 : 331 : polcmd = '*';
129 [ + + ]: 216 : else if (strcmp(cmd_name, "select") == 0)
130 : 85 : polcmd = ACL_SELECT_CHR;
131 [ + + ]: 131 : else if (strcmp(cmd_name, "insert") == 0)
132 : 37 : polcmd = ACL_INSERT_CHR;
133 [ + + ]: 94 : else if (strcmp(cmd_name, "update") == 0)
134 : 63 : polcmd = ACL_UPDATE_CHR;
135 [ + - ]: 31 : else if (strcmp(cmd_name, "delete") == 0)
136 : 31 : polcmd = ACL_DELETE_CHR;
137 : : else
138 [ # # ]: 0 : elog(ERROR, "unrecognized policy command");
139 : :
140 : 547 : return polcmd;
141 : : }
142 : :
143 : : /*
144 : : * policy_role_list_to_array
145 : : * helper function to convert a list of RoleSpecs to an array of
146 : : * role id Datums.
147 : : */
148 : : static Datum *
149 : 555 : policy_role_list_to_array(List *roles, int *num_roles)
150 : : {
151 : : Datum *role_oids;
152 : : ListCell *cell;
153 : 555 : int i = 0;
154 : :
155 : : /* Handle no roles being passed in as being for public */
156 [ - + ]: 555 : if (roles == NIL)
157 : : {
158 : 0 : *num_roles = 1;
159 : 0 : role_oids = palloc_array(Datum, *num_roles);
160 : 0 : role_oids[0] = ObjectIdGetDatum(ACL_ID_PUBLIC);
161 : :
162 : 0 : return role_oids;
163 : : }
164 : :
165 : 555 : *num_roles = list_length(roles);
166 : 555 : role_oids = palloc_array(Datum, *num_roles);
167 : :
168 [ + - + + : 672 : foreach(cell, roles)
+ + ]
169 : : {
170 : 583 : RoleSpec *spec = lfirst(cell);
171 : :
172 : : /*
173 : : * PUBLIC covers all roles, so it only makes sense alone.
174 : : */
175 [ + + ]: 583 : if (spec->roletype == ROLESPEC_PUBLIC)
176 : : {
177 [ - + ]: 466 : if (*num_roles != 1)
178 : : {
179 [ # # ]: 0 : ereport(WARNING,
180 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
181 : : errmsg("ignoring specified roles other than PUBLIC"),
182 : : errhint("All roles are members of the PUBLIC role.")));
183 : 0 : *num_roles = 1;
184 : : }
185 : 466 : role_oids[0] = ObjectIdGetDatum(ACL_ID_PUBLIC);
186 : :
187 : 466 : return role_oids;
188 : : }
189 : : else
190 : 117 : role_oids[i++] =
191 : 117 : ObjectIdGetDatum(get_rolespec_oid(spec, false));
192 : : }
193 : :
194 : 89 : return role_oids;
195 : : }
196 : :
197 : : /*
198 : : * Load row security policy from the catalog, and store it in
199 : : * the relation's relcache entry.
200 : : *
201 : : * Note that caller should have verified that pg_class.relrowsecurity
202 : : * is true for this relation.
203 : : */
204 : : void
205 : 1768 : RelationBuildRowSecurity(Relation relation)
206 : : {
207 : : MemoryContext rscxt;
208 : 1768 : MemoryContext oldcxt = CurrentMemoryContext;
209 : : RowSecurityDesc *rsdesc;
210 : : Relation catalog;
211 : : ScanKeyData skey;
212 : : SysScanDesc sscan;
213 : : HeapTuple tuple;
214 : :
215 : : /*
216 : : * Create a memory context to hold everything associated with this
217 : : * relation's row security policy. This makes it easy to clean up during
218 : : * a relcache flush. However, to cover the possibility of an error
219 : : * partway through, we don't make the context long-lived till we're done.
220 : : */
221 : 1768 : rscxt = AllocSetContextCreate(CurrentMemoryContext,
222 : : "row security descriptor",
223 : : ALLOCSET_SMALL_SIZES);
224 : 1768 : MemoryContextCopyAndSetIdentifier(rscxt,
225 : : RelationGetRelationName(relation));
226 : :
227 : 1768 : rsdesc = MemoryContextAllocZero(rscxt, sizeof(RowSecurityDesc));
228 : 1768 : rsdesc->rscxt = rscxt;
229 : :
230 : : /*
231 : : * Now scan pg_policy for RLS policies associated with this relation.
232 : : * Because we use the index on (polrelid, polname), we should consistently
233 : : * visit the rel's policies in name order, at least when system indexes
234 : : * aren't disabled. This simplifies equalRSDesc().
235 : : */
236 : 1768 : catalog = table_open(PolicyRelationId, AccessShareLock);
237 : :
238 : 1768 : ScanKeyInit(&skey,
239 : : Anum_pg_policy_polrelid,
240 : : BTEqualStrategyNumber, F_OIDEQ,
241 : : ObjectIdGetDatum(RelationGetRelid(relation)));
242 : :
243 : 1768 : sscan = systable_beginscan(catalog, PolicyPolrelidPolnameIndexId, true,
244 : : NULL, 1, &skey);
245 : :
246 [ + + ]: 4008 : while (HeapTupleIsValid(tuple = systable_getnext(sscan)))
247 : : {
248 : 2240 : Form_pg_policy policy_form = (Form_pg_policy) GETSTRUCT(tuple);
249 : : RowSecurityPolicy *policy;
250 : : Datum datum;
251 : : bool isnull;
252 : : char *str_value;
253 : :
254 : 2240 : policy = MemoryContextAllocZero(rscxt, sizeof(RowSecurityPolicy));
255 : :
256 : : /*
257 : : * Note: we must be sure that pass-by-reference data gets copied into
258 : : * rscxt. We avoid making that context current over wider spans than
259 : : * we have to, though.
260 : : */
261 : :
262 : : /* Get policy command */
263 : 2240 : policy->polcmd = policy_form->polcmd;
264 : :
265 : : /* Get policy, permissive or restrictive */
266 : 2240 : policy->permissive = policy_form->polpermissive;
267 : :
268 : : /* Get policy name */
269 : 2240 : policy->policy_name =
270 : 2240 : MemoryContextStrdup(rscxt, NameStr(policy_form->polname));
271 : :
272 : : /* Get policy roles */
273 : 2240 : datum = heap_getattr(tuple, Anum_pg_policy_polroles,
274 : : RelationGetDescr(catalog), &isnull);
275 : : /* shouldn't be null, but let's check for luck */
276 [ - + ]: 2240 : if (isnull)
277 [ # # ]: 0 : elog(ERROR, "unexpected null value in pg_policy.polroles");
278 : 2240 : MemoryContextSwitchTo(rscxt);
279 : 2240 : policy->roles = DatumGetArrayTypePCopy(datum);
280 : 2240 : MemoryContextSwitchTo(oldcxt);
281 : :
282 : : /* Get policy qual */
283 : 2240 : datum = heap_getattr(tuple, Anum_pg_policy_polqual,
284 : : RelationGetDescr(catalog), &isnull);
285 [ + + ]: 2240 : if (!isnull)
286 : : {
287 : 1972 : str_value = TextDatumGetCString(datum);
288 : 1972 : MemoryContextSwitchTo(rscxt);
289 : 1972 : policy->qual = (Expr *) stringToNode(str_value);
290 : 1972 : MemoryContextSwitchTo(oldcxt);
291 : 1972 : pfree(str_value);
292 : : }
293 : : else
294 : 268 : policy->qual = NULL;
295 : :
296 : : /* Get WITH CHECK qual */
297 : 2240 : datum = heap_getattr(tuple, Anum_pg_policy_polwithcheck,
298 : : RelationGetDescr(catalog), &isnull);
299 [ + + ]: 2240 : if (!isnull)
300 : : {
301 : 676 : str_value = TextDatumGetCString(datum);
302 : 676 : MemoryContextSwitchTo(rscxt);
303 : 676 : policy->with_check_qual = (Expr *) stringToNode(str_value);
304 : 676 : MemoryContextSwitchTo(oldcxt);
305 : 676 : pfree(str_value);
306 : : }
307 : : else
308 : 1564 : policy->with_check_qual = NULL;
309 : :
310 : : /* We want to cache whether there are SubLinks in these expressions */
311 [ + + + + ]: 4272 : policy->hassublinks = checkExprHasSubLink((Node *) policy->qual) ||
312 : 2032 : checkExprHasSubLink((Node *) policy->with_check_qual);
313 : :
314 : : /*
315 : : * Add this object to list. For historical reasons, the list is built
316 : : * in reverse order.
317 : : */
318 : 2240 : MemoryContextSwitchTo(rscxt);
319 : 2240 : rsdesc->policies = lcons(policy, rsdesc->policies);
320 : 2240 : MemoryContextSwitchTo(oldcxt);
321 : : }
322 : :
323 : 1768 : systable_endscan(sscan);
324 : 1768 : table_close(catalog, AccessShareLock);
325 : :
326 : : /*
327 : : * Success. Reparent the descriptor's memory context under
328 : : * CacheMemoryContext so that it will live indefinitely, then attach the
329 : : * policy descriptor to the relcache entry.
330 : : */
331 : 1768 : MemoryContextSetParent(rscxt, CacheMemoryContext);
332 : :
333 : 1768 : relation->rd_rsdesc = rsdesc;
334 : 1768 : }
335 : :
336 : : /*
337 : : * RemovePolicyById -
338 : : * remove a policy by its OID. If a policy does not exist with the provided
339 : : * oid, then an error is raised.
340 : : *
341 : : * policy_id - the oid of the policy.
342 : : */
343 : : void
344 : 466 : RemovePolicyById(Oid policy_id)
345 : : {
346 : : Relation pg_policy_rel;
347 : : SysScanDesc sscan;
348 : : ScanKeyData skey[1];
349 : : HeapTuple tuple;
350 : : Oid relid;
351 : : Relation rel;
352 : :
353 : 466 : pg_policy_rel = table_open(PolicyRelationId, RowExclusiveLock);
354 : :
355 : : /*
356 : : * Find the policy to delete.
357 : : */
358 : 466 : ScanKeyInit(&skey[0],
359 : : Anum_pg_policy_oid,
360 : : BTEqualStrategyNumber, F_OIDEQ,
361 : : ObjectIdGetDatum(policy_id));
362 : :
363 : 466 : sscan = systable_beginscan(pg_policy_rel, PolicyOidIndexId, true,
364 : : NULL, 1, skey);
365 : :
366 : 466 : tuple = systable_getnext(sscan);
367 : :
368 : : /* If the policy exists, then remove it, otherwise raise an error. */
369 [ - + ]: 466 : if (!HeapTupleIsValid(tuple))
370 [ # # ]: 0 : elog(ERROR, "could not find tuple for policy %u", policy_id);
371 : :
372 : : /*
373 : : * Open and exclusive-lock the relation the policy belongs to. (We need
374 : : * exclusive lock to lock out queries that might otherwise depend on the
375 : : * set of policies the rel has; furthermore we've got to hold the lock
376 : : * till commit.)
377 : : */
378 : 466 : relid = ((Form_pg_policy) GETSTRUCT(tuple))->polrelid;
379 : :
380 : 466 : rel = table_open(relid, AccessExclusiveLock);
381 [ + + ]: 466 : if (rel->rd_rel->relkind != RELKIND_RELATION &&
382 [ - + ]: 36 : rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
383 [ # # ]: 0 : ereport(ERROR,
384 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
385 : : errmsg("\"%s\" is not a table",
386 : : RelationGetRelationName(rel))));
387 : :
388 [ + - - + ]: 466 : if (!allowSystemTableMods && IsSystemRelation(rel))
389 [ # # ]: 0 : ereport(ERROR,
390 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
391 : : errmsg("permission denied: \"%s\" is a system catalog",
392 : : RelationGetRelationName(rel))));
393 : :
394 : 466 : CatalogTupleDelete(pg_policy_rel, &tuple->t_self);
395 : :
396 : 466 : systable_endscan(sscan);
397 : :
398 : : /*
399 : : * Note that, unlike some of the other flags in pg_class, relrowsecurity
400 : : * is not just an indication of if policies exist. When relrowsecurity is
401 : : * set by a user, then all access to the relation must be through a
402 : : * policy. If no policy is defined for the relation then a default-deny
403 : : * policy is created and all records are filtered (except for queries from
404 : : * the owner).
405 : : */
406 : 466 : CacheInvalidateRelcache(rel);
407 : :
408 : 466 : table_close(rel, NoLock);
409 : :
410 : : /* Clean up */
411 : 466 : table_close(pg_policy_rel, RowExclusiveLock);
412 : 466 : }
413 : :
414 : : /*
415 : : * RemoveRoleFromObjectPolicy -
416 : : * remove a role from a policy's applicable-roles list.
417 : : *
418 : : * Returns true if the role was successfully removed from the policy.
419 : : * Returns false if the role was not removed because it would have left
420 : : * polroles empty (which is disallowed, though perhaps it should not be).
421 : : * On false return, the caller should instead drop the policy altogether.
422 : : * Note that a warning is raised and true is returned if we don't own the
423 : : * table, as the policy should be left alone in that case.
424 : : *
425 : : * roleid - the oid of the role to remove
426 : : * classid - should always be PolicyRelationId
427 : : * policy_id - the oid of the policy.
428 : : */
429 : : bool
430 : 33 : RemoveRoleFromObjectPolicy(Oid roleid, Oid classid, Oid policy_id)
431 : : {
432 : : Relation pg_policy_rel;
433 : : SysScanDesc sscan;
434 : : ScanKeyData skey[1];
435 : : HeapTuple tuple;
436 : : Oid relid;
437 : : ArrayType *policy_roles;
438 : : Datum roles_datum;
439 : : Oid *roles;
440 : : int num_roles;
441 : : Datum *role_oids;
442 : : bool attr_isnull;
443 : 33 : bool keep_policy = true;
444 : : int i,
445 : : j;
446 : :
447 : : Assert(classid == PolicyRelationId);
448 : :
449 : 33 : pg_policy_rel = table_open(PolicyRelationId, RowExclusiveLock);
450 : :
451 : : /*
452 : : * Find the policy to update.
453 : : */
454 : 33 : ScanKeyInit(&skey[0],
455 : : Anum_pg_policy_oid,
456 : : BTEqualStrategyNumber, F_OIDEQ,
457 : : ObjectIdGetDatum(policy_id));
458 : :
459 : 33 : sscan = systable_beginscan(pg_policy_rel, PolicyOidIndexId, true,
460 : : NULL, 1, skey);
461 : :
462 : 33 : tuple = systable_getnext(sscan);
463 : :
464 : : /* Raise an error if we don't find the policy. */
465 [ - + ]: 33 : if (!HeapTupleIsValid(tuple))
466 [ # # ]: 0 : elog(ERROR, "could not find tuple for policy %u", policy_id);
467 : :
468 : : /* Identify rel the policy belongs to */
469 : 33 : relid = ((Form_pg_policy) GETSTRUCT(tuple))->polrelid;
470 : :
471 : : /*
472 : : * Only the table owner can remove the role from the policy, so leave it
473 : : * alone if we aren't the owner.
474 : : */
475 [ + + ]: 33 : if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
476 : : {
477 [ + - ]: 4 : ereport(WARNING,
478 : : (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
479 : : errmsg("role \"%s\" could not be removed from policy \"%s\" for table \"%s\"",
480 : : GetUserNameFromId(roleid, false),
481 : : NameStr(((Form_pg_policy) GETSTRUCT(tuple))->polname),
482 : : get_rel_name(relid))));
483 : :
484 : 4 : systable_endscan(sscan);
485 : 4 : table_close(pg_policy_rel, RowExclusiveLock);
486 : :
487 : 4 : return true;
488 : : }
489 : :
490 : : /* Get the current set of roles */
491 : 29 : roles_datum = heap_getattr(tuple,
492 : : Anum_pg_policy_polroles,
493 : : RelationGetDescr(pg_policy_rel),
494 : : &attr_isnull);
495 : :
496 : : Assert(!attr_isnull);
497 : :
498 : 29 : policy_roles = DatumGetArrayTypePCopy(roles_datum);
499 [ - + ]: 29 : roles = (Oid *) ARR_DATA_PTR(policy_roles);
500 : 29 : num_roles = ARR_DIMS(policy_roles)[0];
501 : :
502 : : /*
503 : : * Rebuild the polroles array, without any mentions of the target role.
504 : : * Ordinarily there'd be exactly one, but we must cope with duplicate
505 : : * mentions, since CREATE/ALTER POLICY historically have allowed that.
506 : : */
507 : 29 : role_oids = palloc_array(Datum, num_roles);
508 [ + + ]: 82 : for (i = 0, j = 0; i < num_roles; i++)
509 : : {
510 [ + + ]: 53 : if (roles[i] != roleid)
511 : 16 : role_oids[j++] = ObjectIdGetDatum(roles[i]);
512 : : }
513 : 29 : num_roles = j;
514 : :
515 : : /* If any roles remain, update the policy entry. */
516 [ + + ]: 29 : if (num_roles > 0)
517 : : {
518 : : ArrayType *role_ids;
519 : : Datum values[Natts_pg_policy];
520 : : bool isnull[Natts_pg_policy];
521 : : bool replaces[Natts_pg_policy];
522 : : HeapTuple new_tuple;
523 : : HeapTuple reltup;
524 : : ObjectAddress target;
525 : : ObjectAddress myself;
526 : :
527 : : /* zero-clear */
528 : 16 : memset(values, 0, sizeof(values));
529 : 16 : memset(replaces, 0, sizeof(replaces));
530 : 16 : memset(isnull, 0, sizeof(isnull));
531 : :
532 : : /* This is the array for the new tuple */
533 : 16 : role_ids = construct_array_builtin(role_oids, num_roles, OIDOID);
534 : :
535 : 16 : replaces[Anum_pg_policy_polroles - 1] = true;
536 : 16 : values[Anum_pg_policy_polroles - 1] = PointerGetDatum(role_ids);
537 : :
538 : 16 : new_tuple = heap_modify_tuple(tuple,
539 : : RelationGetDescr(pg_policy_rel),
540 : : values, isnull, replaces);
541 : 16 : CatalogTupleUpdate(pg_policy_rel, &new_tuple->t_self, new_tuple);
542 : :
543 : : /* Remove all the old shared dependencies (roles) */
544 : 16 : deleteSharedDependencyRecordsFor(PolicyRelationId, policy_id, 0);
545 : :
546 : : /* Record the new shared dependencies (roles) */
547 : 16 : myself.classId = PolicyRelationId;
548 : 16 : myself.objectId = policy_id;
549 : 16 : myself.objectSubId = 0;
550 : :
551 : 16 : target.classId = AuthIdRelationId;
552 : 16 : target.objectSubId = 0;
553 [ + + ]: 32 : for (i = 0; i < num_roles; i++)
554 : : {
555 : 16 : target.objectId = DatumGetObjectId(role_oids[i]);
556 : : /* no need for dependency on the public role */
557 [ + - ]: 16 : if (target.objectId != ACL_ID_PUBLIC)
558 : 16 : recordSharedDependencyOn(&myself, &target,
559 : : SHARED_DEPENDENCY_POLICY);
560 : : }
561 : :
562 [ - + ]: 16 : InvokeObjectPostAlterHook(PolicyRelationId, policy_id, 0);
563 : :
564 : 16 : heap_freetuple(new_tuple);
565 : :
566 : : /* Make updates visible */
567 : 16 : CommandCounterIncrement();
568 : :
569 : : /*
570 : : * Invalidate relcache entry for rel the policy belongs to, to force
571 : : * redoing any dependent plans. In case of a race condition where the
572 : : * rel was just dropped, we need do nothing.
573 : : */
574 : 16 : reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
575 [ + - ]: 16 : if (HeapTupleIsValid(reltup))
576 : : {
577 : 16 : CacheInvalidateRelcacheByTuple(reltup);
578 : 16 : ReleaseSysCache(reltup);
579 : : }
580 : : }
581 : : else
582 : : {
583 : : /* No roles would remain, so drop the policy instead. */
584 : 13 : keep_policy = false;
585 : : }
586 : :
587 : : /* Clean up. */
588 : 29 : systable_endscan(sscan);
589 : :
590 : 29 : table_close(pg_policy_rel, RowExclusiveLock);
591 : :
592 : 29 : return keep_policy;
593 : : }
594 : :
595 : : /*
596 : : * CreatePolicy -
597 : : * handles the execution of the CREATE POLICY command.
598 : : *
599 : : * stmt - the CreatePolicyStmt that describes the policy to create.
600 : : */
601 : : ObjectAddress
602 : 547 : CreatePolicy(CreatePolicyStmt *stmt)
603 : : {
604 : : Relation pg_policy_rel;
605 : : Oid policy_id;
606 : : Relation target_table;
607 : : Oid table_id;
608 : : char polcmd;
609 : : Datum *role_oids;
610 : 547 : int nitems = 0;
611 : : ArrayType *role_ids;
612 : : ParseState *qual_pstate;
613 : : ParseState *with_check_pstate;
614 : : ParseNamespaceItem *nsitem;
615 : : Node *qual;
616 : : Node *with_check_qual;
617 : : ScanKeyData skey[2];
618 : : SysScanDesc sscan;
619 : : HeapTuple policy_tuple;
620 : : Datum values[Natts_pg_policy];
621 : : bool isnull[Natts_pg_policy];
622 : : ObjectAddress target;
623 : : ObjectAddress myself;
624 : : int i;
625 : :
626 : : /* Parse command */
627 : 547 : polcmd = parse_policy_command(stmt->cmd_name);
628 : :
629 : : /*
630 : : * If the command is SELECT or DELETE then WITH CHECK should be NULL.
631 : : */
632 [ + + + + ]: 547 : if ((polcmd == ACL_SELECT_CHR || polcmd == ACL_DELETE_CHR)
633 [ - + ]: 116 : && stmt->with_check != NULL)
634 [ # # ]: 0 : ereport(ERROR,
635 : : (errcode(ERRCODE_SYNTAX_ERROR),
636 : : errmsg("WITH CHECK cannot be applied to SELECT or DELETE")));
637 : :
638 : : /*
639 : : * If the command is INSERT then WITH CHECK should be the only expression
640 : : * provided.
641 : : */
642 [ + + - + ]: 547 : if (polcmd == ACL_INSERT_CHR && stmt->qual != NULL)
643 [ # # ]: 0 : ereport(ERROR,
644 : : (errcode(ERRCODE_SYNTAX_ERROR),
645 : : errmsg("only WITH CHECK expression allowed for INSERT")));
646 : :
647 : : /* Collect role ids */
648 : 547 : role_oids = policy_role_list_to_array(stmt->roles, &nitems);
649 : 547 : role_ids = construct_array_builtin(role_oids, nitems, OIDOID);
650 : :
651 : : /* Parse the supplied clause */
652 : 547 : qual_pstate = make_parsestate(NULL);
653 : 547 : with_check_pstate = make_parsestate(NULL);
654 : :
655 : : /* zero-clear */
656 : 547 : memset(values, 0, sizeof(values));
657 : 547 : memset(isnull, 0, sizeof(isnull));
658 : :
659 : : /* Get id of table. Also handles permissions checks. */
660 : 547 : table_id = RangeVarGetRelidExtended(stmt->table, AccessExclusiveLock,
661 : : 0,
662 : : RangeVarCallbackForPolicy,
663 : : stmt);
664 : :
665 : : /* Open target_table to build quals. No additional lock is necessary. */
666 : 542 : target_table = relation_open(table_id, NoLock);
667 : :
668 : : /* Add for the regular security quals */
669 : 542 : nsitem = addRangeTableEntryForRelation(qual_pstate, target_table,
670 : : AccessShareLock,
671 : : NULL, false, false);
672 : 542 : addNSItemToQuery(qual_pstate, nsitem, false, true, true);
673 : :
674 : : /* Add for the with-check quals */
675 : 542 : nsitem = addRangeTableEntryForRelation(with_check_pstate, target_table,
676 : : AccessShareLock,
677 : : NULL, false, false);
678 : 542 : addNSItemToQuery(with_check_pstate, nsitem, false, true, true);
679 : :
680 : 542 : qual = transformWhereClause(qual_pstate,
681 : : stmt->qual,
682 : : EXPR_KIND_POLICY,
683 : : "POLICY");
684 : :
685 : 538 : with_check_qual = transformWhereClause(with_check_pstate,
686 : : stmt->with_check,
687 : : EXPR_KIND_POLICY,
688 : : "POLICY");
689 : :
690 : : /* Fix up collation information */
691 : 538 : assign_expr_collations(qual_pstate, qual);
692 : 538 : assign_expr_collations(with_check_pstate, with_check_qual);
693 : :
694 : : /* Open pg_policy catalog */
695 : 538 : pg_policy_rel = table_open(PolicyRelationId, RowExclusiveLock);
696 : :
697 : : /* Set key - policy's relation id. */
698 : 538 : ScanKeyInit(&skey[0],
699 : : Anum_pg_policy_polrelid,
700 : : BTEqualStrategyNumber, F_OIDEQ,
701 : : ObjectIdGetDatum(table_id));
702 : :
703 : : /* Set key - policy's name. */
704 : 538 : ScanKeyInit(&skey[1],
705 : : Anum_pg_policy_polname,
706 : : BTEqualStrategyNumber, F_NAMEEQ,
707 : 538 : CStringGetDatum(stmt->policy_name));
708 : :
709 : 538 : sscan = systable_beginscan(pg_policy_rel,
710 : : PolicyPolrelidPolnameIndexId, true, NULL, 2,
711 : : skey);
712 : :
713 : 538 : policy_tuple = systable_getnext(sscan);
714 : :
715 : : /* Complain if the policy name already exists for the table */
716 [ + + ]: 538 : if (HeapTupleIsValid(policy_tuple))
717 [ + - ]: 4 : ereport(ERROR,
718 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
719 : : errmsg("policy \"%s\" for table \"%s\" already exists",
720 : : stmt->policy_name, RelationGetRelationName(target_table))));
721 : :
722 : 534 : policy_id = GetNewOidWithIndex(pg_policy_rel, PolicyOidIndexId,
723 : : Anum_pg_policy_oid);
724 : 534 : values[Anum_pg_policy_oid - 1] = ObjectIdGetDatum(policy_id);
725 : 534 : values[Anum_pg_policy_polrelid - 1] = ObjectIdGetDatum(table_id);
726 : 534 : values[Anum_pg_policy_polname - 1] = DirectFunctionCall1(namein,
727 : : CStringGetDatum(stmt->policy_name));
728 : 534 : values[Anum_pg_policy_polcmd - 1] = CharGetDatum(polcmd);
729 : 534 : values[Anum_pg_policy_polpermissive - 1] = BoolGetDatum(stmt->permissive);
730 : 534 : values[Anum_pg_policy_polroles - 1] = PointerGetDatum(role_ids);
731 : :
732 : : /* Add qual if present. */
733 [ + + ]: 534 : if (qual)
734 : 492 : values[Anum_pg_policy_polqual - 1] = CStringGetTextDatum(nodeToString(qual));
735 : : else
736 : 42 : isnull[Anum_pg_policy_polqual - 1] = true;
737 : :
738 : : /* Add WITH CHECK qual if present */
739 [ + + ]: 534 : if (with_check_qual)
740 : 107 : values[Anum_pg_policy_polwithcheck - 1] = CStringGetTextDatum(nodeToString(with_check_qual));
741 : : else
742 : 427 : isnull[Anum_pg_policy_polwithcheck - 1] = true;
743 : :
744 : 534 : policy_tuple = heap_form_tuple(RelationGetDescr(pg_policy_rel), values,
745 : : isnull);
746 : :
747 : 534 : CatalogTupleInsert(pg_policy_rel, policy_tuple);
748 : :
749 : : /* Record Dependencies */
750 : 534 : target.classId = RelationRelationId;
751 : 534 : target.objectId = table_id;
752 : 534 : target.objectSubId = 0;
753 : :
754 : 534 : myself.classId = PolicyRelationId;
755 : 534 : myself.objectId = policy_id;
756 : 534 : myself.objectSubId = 0;
757 : :
758 : 534 : recordDependencyOn(&myself, &target, DEPENDENCY_AUTO);
759 : :
760 : 534 : CheckUsageOnTypesInExpr(qual, qual_pstate->p_rtable, GetUserId());
761 : 530 : recordDependencyOnExpr(&myself, qual, qual_pstate->p_rtable,
762 : : DEPENDENCY_NORMAL);
763 : :
764 : 530 : CheckUsageOnTypesInExpr(with_check_qual, with_check_pstate->p_rtable,
765 : : GetUserId());
766 : 530 : recordDependencyOnExpr(&myself, with_check_qual,
767 : : with_check_pstate->p_rtable, DEPENDENCY_NORMAL);
768 : :
769 : : /* Register role dependencies */
770 : 530 : target.classId = AuthIdRelationId;
771 : 530 : target.objectSubId = 0;
772 [ + + ]: 1084 : for (i = 0; i < nitems; i++)
773 : : {
774 : 554 : target.objectId = DatumGetObjectId(role_oids[i]);
775 : : /* no dependency if public */
776 [ + + ]: 554 : if (target.objectId != ACL_ID_PUBLIC)
777 : 105 : recordSharedDependencyOn(&myself, &target,
778 : : SHARED_DEPENDENCY_POLICY);
779 : : }
780 : :
781 [ - + ]: 530 : InvokeObjectPostCreateHook(PolicyRelationId, policy_id, 0);
782 : :
783 : : /* Invalidate Relation Cache */
784 : 530 : CacheInvalidateRelcache(target_table);
785 : :
786 : : /* Clean up. */
787 : 530 : heap_freetuple(policy_tuple);
788 : 530 : free_parsestate(qual_pstate);
789 : 530 : free_parsestate(with_check_pstate);
790 : 530 : systable_endscan(sscan);
791 : 530 : relation_close(target_table, NoLock);
792 : 530 : table_close(pg_policy_rel, RowExclusiveLock);
793 : :
794 : 530 : return myself;
795 : : }
796 : :
797 : : /*
798 : : * AlterPolicy -
799 : : * handles the execution of the ALTER POLICY command.
800 : : *
801 : : * stmt - the AlterPolicyStmt that describes the policy and how to alter it.
802 : : */
803 : : ObjectAddress
804 : 56 : AlterPolicy(AlterPolicyStmt *stmt)
805 : : {
806 : : Relation pg_policy_rel;
807 : : Oid policy_id;
808 : : Relation target_table;
809 : : Oid table_id;
810 : 56 : Datum *role_oids = NULL;
811 : 56 : int nitems = 0;
812 : 56 : ArrayType *role_ids = NULL;
813 : 56 : List *qual_parse_rtable = NIL;
814 : 56 : List *with_check_parse_rtable = NIL;
815 : 56 : Node *qual = NULL;
816 : 56 : Node *with_check_qual = NULL;
817 : : ScanKeyData skey[2];
818 : : SysScanDesc sscan;
819 : : HeapTuple policy_tuple;
820 : : HeapTuple new_tuple;
821 : : Datum values[Natts_pg_policy];
822 : : bool isnull[Natts_pg_policy];
823 : : bool replaces[Natts_pg_policy];
824 : : ObjectAddress target;
825 : : ObjectAddress myself;
826 : : Datum polcmd_datum;
827 : : char polcmd;
828 : : bool polcmd_isnull;
829 : : int i;
830 : :
831 : : /* Parse role_ids */
832 [ + + ]: 56 : if (stmt->roles != NULL)
833 : : {
834 : 8 : role_oids = policy_role_list_to_array(stmt->roles, &nitems);
835 : 8 : role_ids = construct_array_builtin(role_oids, nitems, OIDOID);
836 : : }
837 : :
838 : : /* Get id of table. Also handles permissions checks. */
839 : 56 : table_id = RangeVarGetRelidExtended(stmt->table, AccessExclusiveLock,
840 : : 0,
841 : : RangeVarCallbackForPolicy,
842 : : stmt);
843 : :
844 : 48 : target_table = relation_open(table_id, NoLock);
845 : :
846 : : /* Parse the using policy clause */
847 [ + + ]: 48 : if (stmt->qual)
848 : : {
849 : : ParseNamespaceItem *nsitem;
850 : 44 : ParseState *qual_pstate = make_parsestate(NULL);
851 : :
852 : 44 : nsitem = addRangeTableEntryForRelation(qual_pstate, target_table,
853 : : AccessShareLock,
854 : : NULL, false, false);
855 : :
856 : 44 : addNSItemToQuery(qual_pstate, nsitem, false, true, true);
857 : :
858 : 44 : qual = transformWhereClause(qual_pstate, stmt->qual,
859 : : EXPR_KIND_POLICY,
860 : : "POLICY");
861 : :
862 : : /* Fix up collation information */
863 : 44 : assign_expr_collations(qual_pstate, qual);
864 : :
865 : 44 : qual_parse_rtable = qual_pstate->p_rtable;
866 : 44 : free_parsestate(qual_pstate);
867 : : }
868 : :
869 : : /* Parse the with-check policy clause */
870 [ - + ]: 48 : if (stmt->with_check)
871 : : {
872 : : ParseNamespaceItem *nsitem;
873 : 0 : ParseState *with_check_pstate = make_parsestate(NULL);
874 : :
875 : 0 : nsitem = addRangeTableEntryForRelation(with_check_pstate, target_table,
876 : : AccessShareLock,
877 : : NULL, false, false);
878 : :
879 : 0 : addNSItemToQuery(with_check_pstate, nsitem, false, true, true);
880 : :
881 : 0 : with_check_qual = transformWhereClause(with_check_pstate,
882 : : stmt->with_check,
883 : : EXPR_KIND_POLICY,
884 : : "POLICY");
885 : :
886 : : /* Fix up collation information */
887 : 0 : assign_expr_collations(with_check_pstate, with_check_qual);
888 : :
889 : 0 : with_check_parse_rtable = with_check_pstate->p_rtable;
890 : 0 : free_parsestate(with_check_pstate);
891 : : }
892 : :
893 : : /* zero-clear */
894 : 48 : memset(values, 0, sizeof(values));
895 : 48 : memset(replaces, 0, sizeof(replaces));
896 : 48 : memset(isnull, 0, sizeof(isnull));
897 : :
898 : : /* Find policy to update. */
899 : 48 : pg_policy_rel = table_open(PolicyRelationId, RowExclusiveLock);
900 : :
901 : : /* Set key - policy's relation id. */
902 : 48 : ScanKeyInit(&skey[0],
903 : : Anum_pg_policy_polrelid,
904 : : BTEqualStrategyNumber, F_OIDEQ,
905 : : ObjectIdGetDatum(table_id));
906 : :
907 : : /* Set key - policy's name. */
908 : 48 : ScanKeyInit(&skey[1],
909 : : Anum_pg_policy_polname,
910 : : BTEqualStrategyNumber, F_NAMEEQ,
911 : 48 : CStringGetDatum(stmt->policy_name));
912 : :
913 : 48 : sscan = systable_beginscan(pg_policy_rel,
914 : : PolicyPolrelidPolnameIndexId, true, NULL, 2,
915 : : skey);
916 : :
917 : 48 : policy_tuple = systable_getnext(sscan);
918 : :
919 : : /* Check that the policy is found, raise an error if not. */
920 [ - + ]: 48 : if (!HeapTupleIsValid(policy_tuple))
921 [ # # ]: 0 : ereport(ERROR,
922 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
923 : : errmsg("policy \"%s\" for table \"%s\" does not exist",
924 : : stmt->policy_name,
925 : : RelationGetRelationName(target_table))));
926 : :
927 : : /* Get policy command */
928 : 48 : polcmd_datum = heap_getattr(policy_tuple, Anum_pg_policy_polcmd,
929 : : RelationGetDescr(pg_policy_rel),
930 : : &polcmd_isnull);
931 : : Assert(!polcmd_isnull);
932 : 48 : polcmd = DatumGetChar(polcmd_datum);
933 : :
934 : : /*
935 : : * If the command is SELECT or DELETE then WITH CHECK should be NULL.
936 : : */
937 [ + - - + ]: 48 : if ((polcmd == ACL_SELECT_CHR || polcmd == ACL_DELETE_CHR)
938 [ # # ]: 0 : && stmt->with_check != NULL)
939 [ # # ]: 0 : ereport(ERROR,
940 : : (errcode(ERRCODE_SYNTAX_ERROR),
941 : : errmsg("only USING expression allowed for SELECT, DELETE")));
942 : :
943 : : /*
944 : : * If the command is INSERT then WITH CHECK should be the only expression
945 : : * provided.
946 : : */
947 [ - + ]: 48 : if ((polcmd == ACL_INSERT_CHR)
948 [ # # ]: 0 : && stmt->qual != NULL)
949 [ # # ]: 0 : ereport(ERROR,
950 : : (errcode(ERRCODE_SYNTAX_ERROR),
951 : : errmsg("only WITH CHECK expression allowed for INSERT")));
952 : :
953 : 48 : policy_id = ((Form_pg_policy) GETSTRUCT(policy_tuple))->oid;
954 : :
955 [ + + ]: 48 : if (role_ids != NULL)
956 : : {
957 : 8 : replaces[Anum_pg_policy_polroles - 1] = true;
958 : 8 : values[Anum_pg_policy_polroles - 1] = PointerGetDatum(role_ids);
959 : : }
960 : : else
961 : : {
962 : : Oid *roles;
963 : : Datum roles_datum;
964 : : bool attr_isnull;
965 : : ArrayType *policy_roles;
966 : :
967 : : /*
968 : : * We need to pull the set of roles this policy applies to from what's
969 : : * in the catalog, so that we can recreate the dependencies correctly
970 : : * for the policy.
971 : : */
972 : :
973 : 40 : roles_datum = heap_getattr(policy_tuple, Anum_pg_policy_polroles,
974 : : RelationGetDescr(pg_policy_rel),
975 : : &attr_isnull);
976 : : Assert(!attr_isnull);
977 : :
978 : 40 : policy_roles = DatumGetArrayTypePCopy(roles_datum);
979 : :
980 [ - + ]: 40 : roles = (Oid *) ARR_DATA_PTR(policy_roles);
981 : :
982 : 40 : nitems = ARR_DIMS(policy_roles)[0];
983 : :
984 : 40 : role_oids = palloc_array(Datum, nitems);
985 : :
986 [ + + ]: 84 : for (i = 0; i < nitems; i++)
987 : 44 : role_oids[i] = ObjectIdGetDatum(roles[i]);
988 : : }
989 : :
990 [ + + ]: 48 : if (qual != NULL)
991 : : {
992 : 44 : replaces[Anum_pg_policy_polqual - 1] = true;
993 : : values[Anum_pg_policy_polqual - 1]
994 : 44 : = CStringGetTextDatum(nodeToString(qual));
995 : : }
996 : : else
997 : : {
998 : : Datum value_datum;
999 : : bool attr_isnull;
1000 : :
1001 : : /*
1002 : : * We need to pull the USING expression and build the range table for
1003 : : * the policy from what's in the catalog, so that we can recreate the
1004 : : * dependencies correctly for the policy.
1005 : : */
1006 : :
1007 : : /* Check if the policy has a USING expr */
1008 : 4 : value_datum = heap_getattr(policy_tuple, Anum_pg_policy_polqual,
1009 : : RelationGetDescr(pg_policy_rel),
1010 : : &attr_isnull);
1011 [ + - ]: 4 : if (!attr_isnull)
1012 : : {
1013 : : char *qual_value;
1014 : : ParseState *qual_pstate;
1015 : :
1016 : : /* parsestate is built just to build the range table */
1017 : 4 : qual_pstate = make_parsestate(NULL);
1018 : :
1019 : 4 : qual_value = TextDatumGetCString(value_datum);
1020 : 4 : qual = stringToNode(qual_value);
1021 : :
1022 : : /* Add this rel to the parsestate's rangetable, for dependencies */
1023 : 4 : (void) addRangeTableEntryForRelation(qual_pstate, target_table,
1024 : : AccessShareLock,
1025 : : NULL, false, false);
1026 : :
1027 : 4 : qual_parse_rtable = qual_pstate->p_rtable;
1028 : 4 : free_parsestate(qual_pstate);
1029 : : }
1030 : : }
1031 : :
1032 [ - + ]: 48 : if (with_check_qual != NULL)
1033 : : {
1034 : 0 : replaces[Anum_pg_policy_polwithcheck - 1] = true;
1035 : : values[Anum_pg_policy_polwithcheck - 1]
1036 : 0 : = CStringGetTextDatum(nodeToString(with_check_qual));
1037 : : }
1038 : : else
1039 : : {
1040 : : Datum value_datum;
1041 : : bool attr_isnull;
1042 : :
1043 : : /*
1044 : : * We need to pull the WITH CHECK expression and build the range table
1045 : : * for the policy from what's in the catalog, so that we can recreate
1046 : : * the dependencies correctly for the policy.
1047 : : */
1048 : :
1049 : : /* Check if the policy has a WITH CHECK expr */
1050 : 48 : value_datum = heap_getattr(policy_tuple, Anum_pg_policy_polwithcheck,
1051 : : RelationGetDescr(pg_policy_rel),
1052 : : &attr_isnull);
1053 [ - + ]: 48 : if (!attr_isnull)
1054 : : {
1055 : : char *with_check_value;
1056 : : ParseState *with_check_pstate;
1057 : :
1058 : : /* parsestate is built just to build the range table */
1059 : 0 : with_check_pstate = make_parsestate(NULL);
1060 : :
1061 : 0 : with_check_value = TextDatumGetCString(value_datum);
1062 : 0 : with_check_qual = stringToNode(with_check_value);
1063 : :
1064 : : /* Add this rel to the parsestate's rangetable, for dependencies */
1065 : 0 : (void) addRangeTableEntryForRelation(with_check_pstate,
1066 : : target_table,
1067 : : AccessShareLock,
1068 : : NULL, false, false);
1069 : :
1070 : 0 : with_check_parse_rtable = with_check_pstate->p_rtable;
1071 : 0 : free_parsestate(with_check_pstate);
1072 : : }
1073 : : }
1074 : :
1075 : 48 : new_tuple = heap_modify_tuple(policy_tuple,
1076 : : RelationGetDescr(pg_policy_rel),
1077 : : values, isnull, replaces);
1078 : 48 : CatalogTupleUpdate(pg_policy_rel, &new_tuple->t_self, new_tuple);
1079 : :
1080 : : /* Update Dependencies. */
1081 : 48 : deleteDependencyRecordsFor(PolicyRelationId, policy_id, false);
1082 : :
1083 : : /* Record Dependencies */
1084 : 48 : target.classId = RelationRelationId;
1085 : 48 : target.objectId = table_id;
1086 : 48 : target.objectSubId = 0;
1087 : :
1088 : 48 : myself.classId = PolicyRelationId;
1089 : 48 : myself.objectId = policy_id;
1090 : 48 : myself.objectSubId = 0;
1091 : :
1092 : 48 : recordDependencyOn(&myself, &target, DEPENDENCY_AUTO);
1093 : :
1094 [ + + ]: 48 : if (stmt->qual)
1095 : 44 : CheckUsageOnTypesInExpr(qual, qual_parse_rtable, GetUserId());
1096 : 48 : recordDependencyOnExpr(&myself, qual, qual_parse_rtable, DEPENDENCY_NORMAL);
1097 : :
1098 [ - + ]: 48 : if (stmt->with_check)
1099 : 0 : CheckUsageOnTypesInExpr(with_check_qual, with_check_parse_rtable,
1100 : : GetUserId());
1101 : 48 : recordDependencyOnExpr(&myself, with_check_qual, with_check_parse_rtable,
1102 : : DEPENDENCY_NORMAL);
1103 : :
1104 : : /* Register role dependencies */
1105 : 48 : deleteSharedDependencyRecordsFor(PolicyRelationId, policy_id, 0);
1106 : 48 : target.classId = AuthIdRelationId;
1107 : 48 : target.objectSubId = 0;
1108 [ + + ]: 104 : for (i = 0; i < nitems; i++)
1109 : : {
1110 : 56 : target.objectId = DatumGetObjectId(role_oids[i]);
1111 : : /* no dependency if public */
1112 [ + + ]: 56 : if (target.objectId != ACL_ID_PUBLIC)
1113 : 20 : recordSharedDependencyOn(&myself, &target,
1114 : : SHARED_DEPENDENCY_POLICY);
1115 : : }
1116 : :
1117 [ - + ]: 48 : InvokeObjectPostAlterHook(PolicyRelationId, policy_id, 0);
1118 : :
1119 : 48 : heap_freetuple(new_tuple);
1120 : :
1121 : : /* Invalidate Relation Cache */
1122 : 48 : CacheInvalidateRelcache(target_table);
1123 : :
1124 : : /* Clean up. */
1125 : 48 : systable_endscan(sscan);
1126 : 48 : relation_close(target_table, NoLock);
1127 : 48 : table_close(pg_policy_rel, RowExclusiveLock);
1128 : :
1129 : 48 : return myself;
1130 : : }
1131 : :
1132 : : /*
1133 : : * rename_policy -
1134 : : * change the name of a policy on a relation
1135 : : */
1136 : : ObjectAddress
1137 : 12 : rename_policy(RenameStmt *stmt)
1138 : : {
1139 : : Relation pg_policy_rel;
1140 : : Relation target_table;
1141 : : Oid table_id;
1142 : : Oid opoloid;
1143 : : ScanKeyData skey[2];
1144 : : SysScanDesc sscan;
1145 : : HeapTuple policy_tuple;
1146 : : ObjectAddress address;
1147 : :
1148 : : /* Get id of table. Also handles permissions checks. */
1149 : 12 : table_id = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
1150 : : 0,
1151 : : RangeVarCallbackForPolicy,
1152 : : stmt);
1153 : :
1154 : 12 : target_table = relation_open(table_id, NoLock);
1155 : :
1156 : 12 : pg_policy_rel = table_open(PolicyRelationId, RowExclusiveLock);
1157 : :
1158 : : /* First pass -- check for conflict */
1159 : :
1160 : : /* Add key - policy's relation id. */
1161 : 12 : ScanKeyInit(&skey[0],
1162 : : Anum_pg_policy_polrelid,
1163 : : BTEqualStrategyNumber, F_OIDEQ,
1164 : : ObjectIdGetDatum(table_id));
1165 : :
1166 : : /* Add key - policy's name. */
1167 : 12 : ScanKeyInit(&skey[1],
1168 : : Anum_pg_policy_polname,
1169 : : BTEqualStrategyNumber, F_NAMEEQ,
1170 : 12 : CStringGetDatum(stmt->newname));
1171 : :
1172 : 12 : sscan = systable_beginscan(pg_policy_rel,
1173 : : PolicyPolrelidPolnameIndexId, true, NULL, 2,
1174 : : skey);
1175 : :
1176 [ + + ]: 12 : if (HeapTupleIsValid(systable_getnext(sscan)))
1177 [ + - ]: 4 : ereport(ERROR,
1178 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
1179 : : errmsg("policy \"%s\" for table \"%s\" already exists",
1180 : : stmt->newname, RelationGetRelationName(target_table))));
1181 : :
1182 : 8 : systable_endscan(sscan);
1183 : :
1184 : : /* Second pass -- find existing policy and update */
1185 : : /* Add key - policy's relation id. */
1186 : 8 : ScanKeyInit(&skey[0],
1187 : : Anum_pg_policy_polrelid,
1188 : : BTEqualStrategyNumber, F_OIDEQ,
1189 : : ObjectIdGetDatum(table_id));
1190 : :
1191 : : /* Add key - policy's name. */
1192 : 8 : ScanKeyInit(&skey[1],
1193 : : Anum_pg_policy_polname,
1194 : : BTEqualStrategyNumber, F_NAMEEQ,
1195 : 8 : CStringGetDatum(stmt->subname));
1196 : :
1197 : 8 : sscan = systable_beginscan(pg_policy_rel,
1198 : : PolicyPolrelidPolnameIndexId, true, NULL, 2,
1199 : : skey);
1200 : :
1201 : 8 : policy_tuple = systable_getnext(sscan);
1202 : :
1203 : : /* Complain if we did not find the policy */
1204 [ - + ]: 8 : if (!HeapTupleIsValid(policy_tuple))
1205 [ # # ]: 0 : ereport(ERROR,
1206 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
1207 : : errmsg("policy \"%s\" for table \"%s\" does not exist",
1208 : : stmt->subname, RelationGetRelationName(target_table))));
1209 : :
1210 : 8 : opoloid = ((Form_pg_policy) GETSTRUCT(policy_tuple))->oid;
1211 : :
1212 : 8 : policy_tuple = heap_copytuple(policy_tuple);
1213 : :
1214 : 8 : namestrcpy(&((Form_pg_policy) GETSTRUCT(policy_tuple))->polname,
1215 : 8 : stmt->newname);
1216 : :
1217 : 8 : CatalogTupleUpdate(pg_policy_rel, &policy_tuple->t_self, policy_tuple);
1218 : :
1219 [ - + ]: 8 : InvokeObjectPostAlterHook(PolicyRelationId, opoloid, 0);
1220 : :
1221 : 8 : ObjectAddressSet(address, PolicyRelationId, opoloid);
1222 : :
1223 : : /*
1224 : : * Invalidate relation's relcache entry so that other backends (and this
1225 : : * one too!) are sent SI message to make them rebuild relcache entries.
1226 : : * (Ideally this should happen automatically...)
1227 : : */
1228 : 8 : CacheInvalidateRelcache(target_table);
1229 : :
1230 : : /* Clean up. */
1231 : 8 : systable_endscan(sscan);
1232 : 8 : table_close(pg_policy_rel, RowExclusiveLock);
1233 : 8 : relation_close(target_table, NoLock);
1234 : :
1235 : 8 : return address;
1236 : : }
1237 : :
1238 : : /*
1239 : : * get_relation_policy_oid - Look up a policy by name to find its OID
1240 : : *
1241 : : * If missing_ok is false, throw an error if policy not found. If
1242 : : * true, just return InvalidOid.
1243 : : */
1244 : : Oid
1245 : 134 : get_relation_policy_oid(Oid relid, const char *policy_name, bool missing_ok)
1246 : : {
1247 : : Relation pg_policy_rel;
1248 : : ScanKeyData skey[2];
1249 : : SysScanDesc sscan;
1250 : : HeapTuple policy_tuple;
1251 : : Oid policy_oid;
1252 : :
1253 : 134 : pg_policy_rel = table_open(PolicyRelationId, AccessShareLock);
1254 : :
1255 : : /* Add key - policy's relation id. */
1256 : 134 : ScanKeyInit(&skey[0],
1257 : : Anum_pg_policy_polrelid,
1258 : : BTEqualStrategyNumber, F_OIDEQ,
1259 : : ObjectIdGetDatum(relid));
1260 : :
1261 : : /* Add key - policy's name. */
1262 : 134 : ScanKeyInit(&skey[1],
1263 : : Anum_pg_policy_polname,
1264 : : BTEqualStrategyNumber, F_NAMEEQ,
1265 : : CStringGetDatum(policy_name));
1266 : :
1267 : 134 : sscan = systable_beginscan(pg_policy_rel,
1268 : : PolicyPolrelidPolnameIndexId, true, NULL, 2,
1269 : : skey);
1270 : :
1271 : 134 : policy_tuple = systable_getnext(sscan);
1272 : :
1273 [ + + ]: 134 : if (!HeapTupleIsValid(policy_tuple))
1274 : : {
1275 [ + - ]: 8 : if (!missing_ok)
1276 [ + - ]: 8 : ereport(ERROR,
1277 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
1278 : : errmsg("policy \"%s\" for table \"%s\" does not exist",
1279 : : policy_name, get_rel_name(relid))));
1280 : :
1281 : 0 : policy_oid = InvalidOid;
1282 : : }
1283 : : else
1284 : 126 : policy_oid = ((Form_pg_policy) GETSTRUCT(policy_tuple))->oid;
1285 : :
1286 : : /* Clean up. */
1287 : 126 : systable_endscan(sscan);
1288 : 126 : table_close(pg_policy_rel, AccessShareLock);
1289 : :
1290 : 126 : return policy_oid;
1291 : : }
1292 : :
1293 : : /*
1294 : : * relation_has_policies - Determine if relation has any policies
1295 : : */
1296 : : bool
1297 : 0 : relation_has_policies(Relation rel)
1298 : : {
1299 : : Relation catalog;
1300 : : ScanKeyData skey;
1301 : : SysScanDesc sscan;
1302 : : HeapTuple policy_tuple;
1303 : 0 : bool ret = false;
1304 : :
1305 : 0 : catalog = table_open(PolicyRelationId, AccessShareLock);
1306 : 0 : ScanKeyInit(&skey,
1307 : : Anum_pg_policy_polrelid,
1308 : : BTEqualStrategyNumber, F_OIDEQ,
1309 : : ObjectIdGetDatum(RelationGetRelid(rel)));
1310 : 0 : sscan = systable_beginscan(catalog, PolicyPolrelidPolnameIndexId, true,
1311 : : NULL, 1, &skey);
1312 : 0 : policy_tuple = systable_getnext(sscan);
1313 [ # # ]: 0 : if (HeapTupleIsValid(policy_tuple))
1314 : 0 : ret = true;
1315 : :
1316 : 0 : systable_endscan(sscan);
1317 : 0 : table_close(catalog, AccessShareLock);
1318 : :
1319 : 0 : return ret;
1320 : : }
|