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