mirror of https://github.com/postgres/postgres
Building on the updatable security-barrier views work, add the ability to define policies on tables to limit the set of rows which are returned from a query and which are allowed to be added to a table. Expressions defined by the policy for filtering are added to the security barrier quals of the query, while expressions defined to check records being added to a table are added to the with-check options of the query. New top-level commands are CREATE/ALTER/DROP POLICY and are controlled by the table owner. Row Security is able to be enabled and disabled by the owner on a per-table basis using ALTER TABLE .. ENABLE/DISABLE ROW SECURITY. Per discussion, ROW SECURITY is disabled on tables by default and must be enabled for policies on the table to be used. If no policies exist on a table with ROW SECURITY enabled, a default-deny policy is used and no records will be visible. By default, row security is applied at all times except for the table owner and the superuser. A new GUC, row_security, is added which can be set to ON, OFF, or FORCE. When set to FORCE, row security will be applied even for the table owner and superusers. When set to OFF, row security will be disabled when allowed and an error will be thrown if the user does not have rights to bypass row security. Per discussion, pg_dump sets row_security = OFF by default to ensure that exports and backups will have all data in the table or will error if there are insufficient privileges to bypass row security. A new option has been added to pg_dump, --enable-row-security, to ask pg_dump to export with row security enabled. A new role capability, BYPASSRLS, which can only be set by the superuser, is added to allow other users to be able to bypass row security using row_security = OFF. Many thanks to the various individuals who have helped with the design, particularly Robert Haas for his feedback. Authors include Craig Ringer, KaiGai Kohei, Adam Brightwell, Dean Rasheed, with additional changes and rework by me. Reviewers have included all of the above, Greg Smith, Jeff McCormick, and Robert Haas.pull/14/head
parent
e5603a2f35
commit
491c029dbc
@ -0,0 +1,135 @@ |
||||
<!-- |
||||
doc/src/sgml/ref/alter_policy.sgml |
||||
PostgreSQL documentation |
||||
--> |
||||
|
||||
<refentry id="SQL-ALTERPOLICY"> |
||||
<indexterm zone="sql-alterpolicy"> |
||||
<primary>ALTER POLICY</primary> |
||||
</indexterm> |
||||
|
||||
<refmeta> |
||||
<refentrytitle>ALTER POLICY</refentrytitle> |
||||
<manvolnum>7</manvolnum> |
||||
<refmiscinfo>SQL - Language Statements</refmiscinfo> |
||||
</refmeta> |
||||
|
||||
<refnamediv> |
||||
<refname>ALTER POLICY</refname> |
||||
<refpurpose>change the definition of a row-security policy</refpurpose> |
||||
</refnamediv> |
||||
|
||||
<refsynopsisdiv> |
||||
<synopsis> |
||||
ALTER POLICY <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table_name</replaceable> |
||||
[ RENAME TO <replaceable class="PARAMETER">new_name</replaceable> ] |
||||
[ TO { <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] ] |
||||
[ USING ( <replaceable class="parameter">expression</replaceable> ) ] |
||||
[ WITH CHECK ( <replaceable class="parameter">check_expression</replaceable> ) ] |
||||
</synopsis> |
||||
</refsynopsisdiv> |
||||
|
||||
<refsect1> |
||||
<title>Description</title> |
||||
|
||||
<para> |
||||
<command>ALTER POLICY</command> changes the <replaceable class="parameter"> |
||||
definition</replaceable> of an existing row-security policy. |
||||
</para> |
||||
|
||||
<para> |
||||
To use <command>ALTER POLICY</command>, you must own the table that |
||||
the policy applies to. |
||||
</para> |
||||
</refsect1> |
||||
|
||||
<refsect1> |
||||
<title>Parameters</title> |
||||
|
||||
<variablelist> |
||||
<varlistentry> |
||||
<term><replaceable class="parameter">name</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
The name of an existing policy to alter. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry> |
||||
<term><replaceable class="parameter">table_name</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
The name (optionally schema-qualified) of the table that the |
||||
policy is on. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry> |
||||
<term><replaceable class="parameter">new_name</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
The new name for the policy. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry> |
||||
<term><replaceable class="parameter">role_name</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
The role to which the policy applies. Multiple roles can be specified at one time. |
||||
To apply the policy to all roles, use <literal>PUBLIC</literal>, which is also |
||||
the default. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry> |
||||
<term><replaceable class="parameter">expression</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
The USING expression for the policy. This expression will be added as a |
||||
security-barrier qualification to queries which use the table |
||||
automatically. If multiple policies are being applied for a given |
||||
table then they are all combined and added using OR. The USING |
||||
expression applies to records which are being retrived from the table. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry> |
||||
<term><replaceable class="parameter">check_expression</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
The with-check expression for the policy. This expression will be |
||||
added as a WITH CHECK OPTION qualification to queries which use the |
||||
table automatically. If multiple policies are being applied for a |
||||
given table then they are all combined and added using OR. The WITH |
||||
CHECK expression applies to records which are being added to the table. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
</variablelist> |
||||
</refsect1> |
||||
|
||||
<refsect1> |
||||
<title>Compatibility</title> |
||||
|
||||
<para> |
||||
<command>ALTER POLICY</command> is a <productname>PostgreSQL</productname> extension. |
||||
</para> |
||||
</refsect1> |
||||
|
||||
<refsect1> |
||||
<title>See Also</title> |
||||
|
||||
<simplelist type="inline"> |
||||
<member><xref linkend="sql-createpolicy"></member> |
||||
<member><xref linkend="sql-droppolicy"></member> |
||||
</simplelist> |
||||
</refsect1> |
||||
|
||||
</refentry> |
||||
@ -0,0 +1,318 @@ |
||||
<!-- |
||||
doc/src/sgml/ref/create_policy.sgml |
||||
PostgreSQL documentation |
||||
--> |
||||
|
||||
<refentry id="SQL-CREATEPOLICY"> |
||||
<indexterm zone="sql-createpolicy"> |
||||
<primary>CREATE POLICY</primary> |
||||
</indexterm> |
||||
|
||||
<refmeta> |
||||
<refentrytitle>CREATE POLICY</refentrytitle> |
||||
<manvolnum>7</manvolnum> |
||||
<refmiscinfo>SQL - Language Statements</refmiscinfo> |
||||
</refmeta> |
||||
|
||||
<refnamediv> |
||||
<refname>CREATE POLICY</refname> |
||||
<refpurpose>define a new row-security policy for a table</refpurpose> |
||||
</refnamediv> |
||||
|
||||
<refsynopsisdiv> |
||||
<synopsis> |
||||
CREATE POLICY <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table_name</replaceable> |
||||
[ FOR { ALL | SELECT | INSERT | UPDATE | DELETE } ] |
||||
[ TO { <replaceable class="parameter">role_name</replaceable> | PUBLIC } [, ...] ] |
||||
[ USING ( <replaceable class="parameter">expression</replaceable> ) ] |
||||
[ WITH CHECK ( <replaceable class="parameter">check_expression</replaceable> ) ] |
||||
</synopsis> |
||||
</refsynopsisdiv> |
||||
|
||||
<refsect1> |
||||
<title>Description</title> |
||||
|
||||
<para> |
||||
The <command>CREATE POLICY</command> command defines a new row-security |
||||
policy for a table. Note that row-security must also be enabled on the |
||||
table using <command>ALTER TABLE</command> in order for created policies |
||||
to be applied. |
||||
</para> |
||||
|
||||
<para> |
||||
A row-security policy is an expression which is added to the security-barrier |
||||
qualifications of queries which are run against the table the policy is on, |
||||
or an expression which is added to the with-check options for a table and |
||||
which is applied to rows which would be added to the table. |
||||
The security-barrier qualifications will always be evaluated prior to any |
||||
user-defined functions or user-provided WHERE clauses, while the with-check |
||||
expression will be evaluated against the rows which are going to be added to |
||||
the table. By adding policies to a table, a user can limit the rows which a |
||||
given user can select, insert, update, or delete. This capability is also |
||||
known as Row-Level Security or RLS. |
||||
</para> |
||||
|
||||
<para> |
||||
Policy names are per-table, therefore one policy name can be used for many |
||||
different tables and have a definition for each table which is appropriate to |
||||
that table. |
||||
</para> |
||||
|
||||
<para> |
||||
Policies can be applied for specific commands or for specific roles. The |
||||
default for newly created policies is that they apply for all commands and |
||||
roles, unless otherwise specified. If multiple policies apply to a given |
||||
query, they will be combined using OR. |
||||
</para> |
||||
|
||||
<para> |
||||
Note that while row-security policies will be applied for explicit queries |
||||
against tables in the system, they are not applied when the system is |
||||
performing internal referential integrity checks or validating constraints. |
||||
This means there are indirect ways to determine that a given value exists. |
||||
An example of this is attempting to insert a duplicate value |
||||
into a column which is the primary key or has a unique constraint. If the |
||||
insert fails then the user can infer that the value already exists (this |
||||
example assumes that the user is permitted by policy to insert |
||||
records which they are not allowed to see). Another example is where a user |
||||
is allowed to insert into a table which references another, otherwise hidden |
||||
table. Existence can be determined by the user inserting values into the |
||||
referencing table, where success would indicate that the value exists in the |
||||
referenced table. These issues can be addressed by carefully crafting |
||||
policies which prevent users from being able to insert, delete, or update |
||||
records at all which might possibly indicate a value they are not otherwise |
||||
able to see, or by using generated values (eg: surrogate keys) instead. |
||||
</para> |
||||
|
||||
<para> |
||||
Regarding how policy expressions interact with the user: as the expressions |
||||
are added to the user's query directly, they will be run with the rights of |
||||
the user running the overall query. Therefore, users who are using a given |
||||
policy must be able to access any tables or functions referenced in the |
||||
expression or they will simply receive a permission denied error when |
||||
attempting to query the RLS-enabled table. This does not change how views |
||||
work, however. As with normal queries and views, permission checks and |
||||
policies for the tables which are referenced by a view will use the view |
||||
owner's rights and any policies which apply to the view owner. |
||||
</para> |
||||
|
||||
</refsect1> |
||||
|
||||
<refsect1> |
||||
<title>Parameters</title> |
||||
|
||||
<variablelist> |
||||
<varlistentry> |
||||
<term><replaceable class="parameter">name</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
The name of the policy to be created. This must be distinct from the |
||||
name of any other policy for the table. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry> |
||||
<term><replaceable class="parameter">table_name</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
The name (optionally schema-qualified) of the table the |
||||
policy applies to. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry> |
||||
<term><replaceable class="parameter">command</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
The command to which the policy applies. Valid options are |
||||
<command>ALL</command>, <command>SELECT</command>, |
||||
<command>INSERT</command>, <command>UPDATE</command>, |
||||
and <command>DELETE</command>. |
||||
<command>ALL</command> is the default. |
||||
See below for specifics regarding how these are applied. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry> |
||||
<term><replaceable class="parameter">role_name</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
The roles to which the policy is to be applied. The default is |
||||
<literal>PUBLIC</literal>, which will apply the policy to all roles. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry> |
||||
<term><replaceable class="parameter">expression</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
Any <acronym>SQL</acronym> conditional expression (returning |
||||
<type>boolean</type>). The conditional expression cannot contain |
||||
any aggregate or window functions. This expression will be added |
||||
to queries to filter out the records which are visible to the query. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry> |
||||
<term><replaceable class="parameter">check_expression</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
Any <acronym>SQL</acronym> conditional expression (returning |
||||
<type>boolean</type>). The condition expression cannot contain |
||||
any aggregate or window functions. This expression will be added |
||||
to queries which are attempting to add records to the table as |
||||
with-check options, and an error will be thrown if this condition |
||||
returns false for any records being added. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
</variablelist> |
||||
</refsect1> |
||||
|
||||
<refsect1> |
||||
<title>Per-Command policies</title> |
||||
|
||||
<variablelist> |
||||
|
||||
<varlistentry id="SQL-CREATEPOLICY-ALL"> |
||||
<term><literal>ALL</></term> |
||||
<listitem> |
||||
<para> |
||||
Using <literal>ALL</literal> for a policy means that it will apply |
||||
to all commands, regardless of the type of command. If an |
||||
<literal>ALL</literal> policy exists and more specific policies |
||||
exist, then both the <literal>ALL</literal> policy and the more |
||||
specific policy (or policies) will be combined using |
||||
<literal>OR</literal>, as usual for overlapping policies. |
||||
Additionally, <literal>ALL</literal> policies will be applied to |
||||
both the selection side of a query and the modification side, using |
||||
the USING policy for both if only a USING policy has been defined. |
||||
|
||||
As an example, if an <literal>UPDATE</literal> is issued, then the |
||||
<literal>ALL</literal> policy will be applicable to both what the |
||||
<literal>UPDATE</literal> will be able to select out as rows to be |
||||
updated (with the USING expression being applied), and it will be |
||||
applied to rows which result from the <literal>UPDATE</literal> |
||||
statement, to check if they are permitted to be added to the table |
||||
(using the WITH CHECK expression, if defined, and the USING expression |
||||
otherwise). If an INSERT or UPDATE command attempts to add rows to |
||||
the table which do not pass the <literal>ALL</literal> WITH CHECK |
||||
(or USING, if no WITH CHECK expression is defined) expression, the |
||||
command will error. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry id="SQL-CREATEPOLICY-SELECT"> |
||||
<term><literal>SELECT</></term> |
||||
<listitem> |
||||
<para> |
||||
Using <literal>SELECT</literal> for a policy means that it will apply |
||||
to <literal>SELECT</literal> commands. The result is that only those |
||||
records from the relation which pass the <literal>SELECT</literal> |
||||
policy will be returned, even if other records exist in the relation. |
||||
The <literal>SELECT</literal> policy only accepts the USING expression |
||||
as it only ever applies in cases where records are being retrived from |
||||
the relation. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry id="SQL-CREATEPOLICY-INSERT"> |
||||
<term><literal>INSERT</></term> |
||||
<listitem> |
||||
<para> |
||||
Using <literal>INSERT</literal> for a policy means that it will apply |
||||
to <literal>INSERT</literal> commands. Rows being inserted which do |
||||
not pass this policy will result in a policy violation ERROR and the |
||||
entire <literal>INSERT</literal> command will be aborted. The |
||||
<literal>INSERT</literal> policy only accepts the WITH CHECK expression |
||||
as it only ever applies in cases where records are being added to the |
||||
relation. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry id="SQL-CREATEPOLICY-UPDATE"> |
||||
<term><literal>DELETE</></term> |
||||
<listitem> |
||||
<para> |
||||
Using <literal>UPDATE</literal> for a policy means that it will apply |
||||
to <literal>UPDATE</literal> commands. As <literal>UPDATE</literal> |
||||
involves pulling an existing record and then making changes to some |
||||
portion (but possibly not all) of the record, the |
||||
<literal>UPDATE</literal> policy accepts both a USING expression and |
||||
a WITH CHECK expression. The USING expression will be used to |
||||
determine which records the <literal>UPDATE</literal> command will |
||||
see to operate against, while the <literal>WITH CHECK</literal> |
||||
expression defines what rows are allowed to be added back into the |
||||
relation (similar to the <literal>INSERT</literal> policy). |
||||
Any rows whose resulting values do not pass the |
||||
<literal>WITH CHECK</literal> expression will cause an ERROR and the |
||||
entire command will be aborted. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry id="SQL-CREATEPOLICY-DELETE"> |
||||
<term><literal>DELETE</></term> |
||||
<listitem> |
||||
<para> |
||||
Using <literal>DELETE</literal> for a policy means that it will apply |
||||
to <literal>DELETE</literal> commands. Only rows which pass this |
||||
policy will be seen by a <literal>DELETE</literal> command. Rows may |
||||
be visible through a <literal>SELECT</literal> which are not seen by a |
||||
<literal>DELETE</literal>, as they do not pass the USING expression |
||||
for the <literal>DELETE</literal>, and rows which are not visible |
||||
through the <literal>SELECT</literal> policy may be deleted if they |
||||
pass the <literal>DELETE</literal> USING policy. The |
||||
<literal>DELETE</literal> policy only accept the USING expression as |
||||
it only ever applies in cases where records are being extracted from |
||||
the relation for deletion. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
</variablelist> |
||||
</refsect1> |
||||
|
||||
<refsect1> |
||||
<title>Notes</title> |
||||
|
||||
<para> |
||||
You must be the owner of a table to create or change policies for it. |
||||
</para> |
||||
|
||||
<para> |
||||
In order to maintain <firstterm>referential integrity</firstterm> between |
||||
two related tables, row-security policies are not applied when the system |
||||
performs checks on foreign key constraints. |
||||
</para> |
||||
|
||||
</refsect1> |
||||
|
||||
<refsect1> |
||||
<title>Compatibility</title> |
||||
|
||||
<para> |
||||
<command>CREATE POLICY</command> is a <productname>PostgreSQL</productname> |
||||
extension. |
||||
</para> |
||||
</refsect1> |
||||
|
||||
<refsect1> |
||||
<title>See Also</title> |
||||
|
||||
<simplelist type="inline"> |
||||
<member><xref linkend="sql-alterpolicy"></member> |
||||
<member><xref linkend="sql-droppolicy"></member> |
||||
</simplelist> |
||||
</refsect1> |
||||
|
||||
</refentry> |
||||
@ -0,0 +1,109 @@ |
||||
<!-- |
||||
doc/src/sgml/ref/drop_policy.sgml |
||||
PostgreSQL documentation |
||||
--> |
||||
|
||||
<refentry id="SQL-DROPPOLICY"> |
||||
<indexterm zone="sql-droppolicy"> |
||||
<primary>DROP POLICY</primary> |
||||
</indexterm> |
||||
|
||||
<refmeta> |
||||
<refentrytitle>DROP POLICY</refentrytitle> |
||||
<manvolnum>7</manvolnum> |
||||
<refmiscinfo>SQL - Language Statements</refmiscinfo> |
||||
</refmeta> |
||||
|
||||
<refnamediv> |
||||
<refname>DROP POLICY</refname> |
||||
<refpurpose>remove a row-security policy from a table</refpurpose> |
||||
</refnamediv> |
||||
|
||||
<refsynopsisdiv> |
||||
<synopsis> |
||||
DROP POLICY [ IF EXISTS ] <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table_name</replaceable> |
||||
</synopsis> |
||||
</refsynopsisdiv> |
||||
|
||||
<refsect1> |
||||
<title>Description</title> |
||||
|
||||
<para> |
||||
<command>DROP POLICY</command> removes the specified row-security policy |
||||
from the table. Note that if the last policy is removed for a table and |
||||
the table still has ROW POLICY enabled via <command>ALTER TABLE</command>, |
||||
then the default-deny policy will be used. <command>ALTER TABLE</command> |
||||
can be used to disable row security for a table using |
||||
<literal>DISABLE ROW SECURITY</literal>, whether policies for the table |
||||
exist or not. |
||||
</para> |
||||
</refsect1> |
||||
|
||||
<refsect1> |
||||
<title>Parameters</title> |
||||
|
||||
<variablelist> |
||||
|
||||
<varlistentry> |
||||
<term><literal>IF EXISTS</literal></term> |
||||
<listitem> |
||||
<para> |
||||
Do not throw an error if the policy does not exist. A notice is issued |
||||
in this case. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry> |
||||
<term><replaceable class="parameter">name</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
The name of the policy to drop. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
<varlistentry> |
||||
<term><replaceable class="parameter">table_name</replaceable></term> |
||||
<listitem> |
||||
<para> |
||||
The name (optionally schema-qualified) of the table that |
||||
the policy is on. |
||||
</para> |
||||
</listitem> |
||||
</varlistentry> |
||||
|
||||
</variablelist> |
||||
</refsect1> |
||||
|
||||
<refsect1> |
||||
<title>Examples</title> |
||||
|
||||
<para> |
||||
To drop the row-security policy called <literal>p1</literal> on the |
||||
table named <literal>my_table</literal>: |
||||
|
||||
<programlisting> |
||||
DROP POLICY p1 ON my_table; |
||||
</programlisting> |
||||
</para> |
||||
</refsect1> |
||||
|
||||
<refsect1> |
||||
<title>Compatibility</title> |
||||
|
||||
<para> |
||||
<command>DROP POLICY</command> is a <productname>PostgreSQL</productname> extension. |
||||
</para> |
||||
</refsect1> |
||||
|
||||
<refsect1> |
||||
<title>See Also</title> |
||||
|
||||
<simplelist type="inline"> |
||||
<member><xref linkend="sql-createpolicy"></member> |
||||
<member><xref linkend="sql-alterpolicy"></member> |
||||
</simplelist> |
||||
</refsect1> |
||||
|
||||
</refentry> |
||||
@ -0,0 +1,988 @@ |
||||
/*-------------------------------------------------------------------------
|
||||
* |
||||
* policy.c |
||||
* Commands for manipulating policies. |
||||
* |
||||
* Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
* |
||||
* src/backend/commands/policy.c |
||||
* |
||||
*------------------------------------------------------------------------- |
||||
*/ |
||||
#include "postgres.h" |
||||
|
||||
#include "access/genam.h" |
||||
#include "access/heapam.h" |
||||
#include "access/htup.h" |
||||
#include "access/htup_details.h" |
||||
#include "access/sysattr.h" |
||||
#include "catalog/catalog.h" |
||||
#include "catalog/dependency.h" |
||||
#include "catalog/indexing.h" |
||||
#include "catalog/namespace.h" |
||||
#include "catalog/objectaccess.h" |
||||
#include "catalog/pg_rowsecurity.h" |
||||
#include "catalog/pg_type.h" |
||||
#include "commands/policy.h" |
||||
#include "miscadmin.h" |
||||
#include "nodes/makefuncs.h" |
||||
#include "nodes/pg_list.h" |
||||
#include "optimizer/clauses.h" |
||||
#include "parser/parse_clause.h" |
||||
#include "parser/parse_node.h" |
||||
#include "parser/parse_relation.h" |
||||
#include "storage/lock.h" |
||||
#include "utils/acl.h" |
||||
#include "utils/array.h" |
||||
#include "utils/builtins.h" |
||||
#include "utils/fmgroids.h" |
||||
#include "utils/inval.h" |
||||
#include "utils/lsyscache.h" |
||||
#include "utils/memutils.h" |
||||
#include "utils/rel.h" |
||||
#include "utils/syscache.h" |
||||
|
||||
static void RangeVarCallbackForPolicy(const RangeVar *rv, |
||||
Oid relid, Oid oldrelid, void *arg); |
||||
static const char parse_row_security_command(const char *cmd_name); |
||||
static ArrayType* rls_role_list_to_array(List *roles); |
||||
|
||||
/*
|
||||
* Callback to RangeVarGetRelidExtended(). |
||||
* |
||||
* Checks the following: |
||||
* - the relation specified is a table. |
||||
* - current user owns the table. |
||||
* - the table is not a system table. |
||||
* |
||||
* If any of these checks fails then an error is raised. |
||||
*/ |
||||
static void |
||||
RangeVarCallbackForPolicy(const RangeVar *rv, Oid relid, Oid oldrelid, |
||||
void *arg) |
||||
{ |
||||
HeapTuple tuple; |
||||
Form_pg_class classform; |
||||
char relkind; |
||||
|
||||
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid)); |
||||
if (!HeapTupleIsValid(tuple)) |
||||
return; |
||||
|
||||
classform = (Form_pg_class) GETSTRUCT(tuple); |
||||
relkind = classform->relkind; |
||||
|
||||
/* Must own relation. */ |
||||
if (!pg_class_ownercheck(relid, GetUserId())) |
||||
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, rv->relname); |
||||
|
||||
/* No system table modifications unless explicitly allowed. */ |
||||
if (!allowSystemTableMods && IsSystemClass(relid, classform)) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), |
||||
errmsg("permission denied: \"%s\" is a system catalog", |
||||
rv->relname))); |
||||
|
||||
/* Relation type MUST be a table. */ |
||||
if (relkind != RELKIND_RELATION) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_WRONG_OBJECT_TYPE), |
||||
errmsg("\"%s\" is not a table", rv->relname))); |
||||
|
||||
ReleaseSysCache(tuple); |
||||
} |
||||
|
||||
/*
|
||||
* parse_row_security_command - |
||||
* helper function to convert full command strings to their char |
||||
* representation. |
||||
* |
||||
* cmd_name - full string command name. Valid values are 'all', 'select', |
||||
* 'insert', 'update' and 'delete'. |
||||
* |
||||
*/ |
||||
static const char |
||||
parse_row_security_command(const char *cmd_name) |
||||
{ |
||||
char cmd; |
||||
|
||||
if (!cmd_name) |
||||
elog(ERROR, "Unregonized command."); |
||||
|
||||
if (strcmp(cmd_name, "all") == 0) |
||||
cmd = 0; |
||||
else if (strcmp(cmd_name, "select") == 0) |
||||
cmd = ACL_SELECT_CHR; |
||||
else if (strcmp(cmd_name, "insert") == 0) |
||||
cmd = ACL_INSERT_CHR; |
||||
else if (strcmp(cmd_name, "update") == 0) |
||||
cmd = ACL_UPDATE_CHR; |
||||
else if (strcmp(cmd_name, "delete") == 0) |
||||
cmd = ACL_DELETE_CHR; |
||||
else |
||||
elog(ERROR, "Unregonized command."); |
||||
/* error unrecognized command */ |
||||
|
||||
return cmd; |
||||
} |
||||
|
||||
/*
|
||||
* rls_role_list_to_array |
||||
* helper function to convert a list of role names in to an array of |
||||
* role ids. |
||||
* |
||||
* Note: If PUBLIC is provided as a role name, then ACL_ID_PUBLIC is |
||||
* used as the role id. |
||||
* |
||||
* roles - the list of role names to convert. |
||||
*/ |
||||
static ArrayType * |
||||
rls_role_list_to_array(List *roles) |
||||
{ |
||||
ArrayType *role_ids; |
||||
Datum *temp_array; |
||||
ListCell *cell; |
||||
int num_roles; |
||||
int i = 0; |
||||
|
||||
/* Handle no roles being passed in as being for public */ |
||||
if (roles == NIL) |
||||
{ |
||||
temp_array = (Datum *) palloc(sizeof(Datum)); |
||||
temp_array[0] = ObjectIdGetDatum(ACL_ID_PUBLIC); |
||||
|
||||
role_ids = construct_array(temp_array, 1, OIDOID, sizeof(Oid), true, |
||||
'i'); |
||||
return role_ids; |
||||
} |
||||
|
||||
num_roles = list_length(roles); |
||||
temp_array = (Datum *) palloc(num_roles * sizeof(Datum)); |
||||
|
||||
foreach(cell, roles) |
||||
{ |
||||
Oid roleid = get_role_oid_or_public(strVal(lfirst(cell))); |
||||
|
||||
/*
|
||||
* PUBLIC covers all roles, so it only makes sense alone. |
||||
*/ |
||||
if (roleid == ACL_ID_PUBLIC) |
||||
{ |
||||
if (num_roles != 1) |
||||
ereport(WARNING, |
||||
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), |
||||
errmsg("ignoring roles specified other than public"), |
||||
errhint("All roles are members of the public role."))); |
||||
|
||||
temp_array[0] = ObjectIdGetDatum(roleid); |
||||
num_roles = 1; |
||||
break; |
||||
} |
||||
else |
||||
temp_array[i++] = ObjectIdGetDatum(roleid); |
||||
} |
||||
|
||||
role_ids = construct_array(temp_array, num_roles, OIDOID, sizeof(Oid), true, |
||||
'i'); |
||||
|
||||
return role_ids; |
||||
} |
||||
|
||||
/*
|
||||
* Load row-security policy from the catalog, and keep it in |
||||
* the relation cache. |
||||
*/ |
||||
void |
||||
RelationBuildRowSecurity(Relation relation) |
||||
{ |
||||
Relation catalog; |
||||
ScanKeyData skey; |
||||
SysScanDesc sscan; |
||||
HeapTuple tuple; |
||||
MemoryContext oldcxt; |
||||
MemoryContext rscxt = NULL; |
||||
RowSecurityDesc *rsdesc = NULL; |
||||
|
||||
catalog = heap_open(RowSecurityRelationId, AccessShareLock); |
||||
|
||||
ScanKeyInit(&skey, |
||||
Anum_pg_rowsecurity_rsecrelid, |
||||
BTEqualStrategyNumber, F_OIDEQ, |
||||
ObjectIdGetDatum(RelationGetRelid(relation))); |
||||
|
||||
sscan = systable_beginscan(catalog, RowSecurityRelidPolnameIndexId, true, |
||||
NULL, 1, &skey); |
||||
PG_TRY(); |
||||
{ |
||||
/*
|
||||
* Set up our memory context- we will always set up some kind of |
||||
* policy here. If no explicit policies are found then an implicit |
||||
* default-deny policy is created. |
||||
*/ |
||||
rscxt = AllocSetContextCreate(CacheMemoryContext, |
||||
"Row-security descriptor", |
||||
ALLOCSET_SMALL_MINSIZE, |
||||
ALLOCSET_SMALL_INITSIZE, |
||||
ALLOCSET_SMALL_MAXSIZE); |
||||
rsdesc = MemoryContextAllocZero(rscxt, sizeof(RowSecurityDesc)); |
||||
rsdesc->rscxt = rscxt; |
||||
|
||||
/*
|
||||
* Loop through the row-level security entries for this relation, if |
||||
* any. |
||||
*/ |
||||
while (HeapTupleIsValid(tuple = systable_getnext(sscan))) |
||||
{ |
||||
Datum value_datum; |
||||
char cmd_value; |
||||
ArrayType *roles; |
||||
char *qual_value; |
||||
Expr *qual_expr; |
||||
char *with_check_value; |
||||
Expr *with_check_qual; |
||||
char *policy_name_value; |
||||
Oid policy_id; |
||||
bool isnull; |
||||
RowSecurityPolicy *policy = NULL; |
||||
|
||||
oldcxt = MemoryContextSwitchTo(rscxt); |
||||
|
||||
/* Get policy command */ |
||||
value_datum = heap_getattr(tuple, Anum_pg_rowsecurity_rseccmd, |
||||
RelationGetDescr(catalog), &isnull); |
||||
if (isnull) |
||||
cmd_value = 0; |
||||
else |
||||
cmd_value = DatumGetChar(value_datum); |
||||
|
||||
/* Get policy name */ |
||||
value_datum = heap_getattr(tuple, Anum_pg_rowsecurity_rsecpolname, |
||||
RelationGetDescr(catalog), &isnull); |
||||
Assert(!isnull); |
||||
policy_name_value = DatumGetCString(value_datum); |
||||
|
||||
/* Get policy roles */ |
||||
value_datum = heap_getattr(tuple, Anum_pg_rowsecurity_rsecroles, |
||||
RelationGetDescr(catalog), &isnull); |
||||
Assert(!isnull); |
||||
roles = DatumGetArrayTypeP(value_datum); |
||||
|
||||
/* Get policy qual */ |
||||
value_datum = heap_getattr(tuple, Anum_pg_rowsecurity_rsecqual, |
||||
RelationGetDescr(catalog), &isnull); |
||||
if (!isnull) |
||||
{ |
||||
qual_value = TextDatumGetCString(value_datum); |
||||
qual_expr = (Expr *) stringToNode(qual_value); |
||||
} |
||||
else |
||||
qual_expr = NULL; |
||||
|
||||
/* Get WITH CHECK qual */ |
||||
value_datum = heap_getattr(tuple, Anum_pg_rowsecurity_rsecwithcheck, |
||||
RelationGetDescr(catalog), &isnull); |
||||
|
||||
if (!isnull) |
||||
{ |
||||
with_check_value = TextDatumGetCString(value_datum); |
||||
with_check_qual = (Expr *) stringToNode(with_check_value); |
||||
} |
||||
else |
||||
with_check_qual = NULL; |
||||
|
||||
policy_id = HeapTupleGetOid(tuple); |
||||
|
||||
policy = palloc0(sizeof(RowSecurityPolicy)); |
||||
policy->policy_name = policy_name_value; |
||||
policy->rsecid = policy_id; |
||||
policy->cmd = cmd_value; |
||||
policy->roles = roles; |
||||
policy->qual = copyObject(qual_expr); |
||||
policy->with_check_qual = copyObject(with_check_qual); |
||||
policy->hassublinks = contain_subplans((Node *) qual_expr) || |
||||
contain_subplans((Node *) with_check_qual); |
||||
|
||||
rsdesc->policies = lcons(policy, rsdesc->policies); |
||||
|
||||
MemoryContextSwitchTo(oldcxt); |
||||
|
||||
if (qual_expr != NULL) |
||||
pfree(qual_expr); |
||||
|
||||
if (with_check_qual != NULL) |
||||
pfree(with_check_qual); |
||||
} |
||||
|
||||
/*
|
||||
* Check if no policies were added |
||||
* |
||||
* If no policies exist in pg_rowsecurity for this relation, then we |
||||
* need to create a single default-deny policy. We use InvalidOid for |
||||
* the Oid to indicate that this is the default-deny policy (we may |
||||
* decide to ignore the default policy if an extension adds policies). |
||||
*/ |
||||
if (rsdesc->policies == NIL) |
||||
{ |
||||
RowSecurityPolicy *policy = NULL; |
||||
Datum role; |
||||
|
||||
oldcxt = MemoryContextSwitchTo(rscxt); |
||||
|
||||
role = ObjectIdGetDatum(ACL_ID_PUBLIC); |
||||
|
||||
policy = palloc0(sizeof(RowSecurityPolicy)); |
||||
policy->policy_name = pstrdup("default-deny policy"); |
||||
policy->rsecid = InvalidOid; |
||||
policy->cmd = '\0'; |
||||
policy->roles = construct_array(&role, 1, OIDOID, sizeof(Oid), true, |
||||
'i'); |
||||
policy->qual = (Expr *) makeConst(BOOLOID, -1, InvalidOid, |
||||
sizeof(bool), BoolGetDatum(false), |
||||
false, true); |
||||
policy->with_check_qual = copyObject(policy->qual); |
||||
policy->hassublinks = false; |
||||
|
||||
rsdesc->policies = lcons(policy, rsdesc->policies); |
||||
|
||||
MemoryContextSwitchTo(oldcxt); |
||||
} |
||||
} |
||||
PG_CATCH(); |
||||
{ |
||||
if (rscxt != NULL) |
||||
MemoryContextDelete(rscxt); |
||||
PG_RE_THROW(); |
||||
} |
||||
PG_END_TRY(); |
||||
|
||||
systable_endscan(sscan); |
||||
heap_close(catalog, AccessShareLock); |
||||
|
||||
relation->rsdesc = rsdesc; |
||||
} |
||||
|
||||
/*
|
||||
* RemovePolicyById - |
||||
* remove a row-security policy by its OID. If a policy does not exist with |
||||
* the provided oid, then an error is raised. |
||||
* |
||||
* policy_id - the oid of the row-security policy. |
||||
*/ |
||||
void |
||||
RemovePolicyById(Oid policy_id) |
||||
{ |
||||
Relation pg_rowsecurity_rel; |
||||
SysScanDesc sscan; |
||||
ScanKeyData skey[1]; |
||||
HeapTuple tuple; |
||||
Oid relid; |
||||
Relation rel; |
||||
|
||||
pg_rowsecurity_rel = heap_open(RowSecurityRelationId, RowExclusiveLock); |
||||
|
||||
/*
|
||||
* Find the policy to delete. |
||||
*/ |
||||
ScanKeyInit(&skey[0], |
||||
ObjectIdAttributeNumber, |
||||
BTEqualStrategyNumber, F_OIDEQ, |
||||
ObjectIdGetDatum(policy_id)); |
||||
|
||||
sscan = systable_beginscan(pg_rowsecurity_rel, RowSecurityOidIndexId, true, |
||||
NULL, 1, skey); |
||||
|
||||
tuple = systable_getnext(sscan); |
||||
|
||||
/* If the policy exists, then remove it, otherwise raise an error. */ |
||||
if (!HeapTupleIsValid(tuple)) |
||||
elog(ERROR, "could not find tuple for row-security %u", policy_id); |
||||
|
||||
/*
|
||||
* Open and exclusive-lock the relation the policy belong to. |
||||
*/ |
||||
relid = ((Form_pg_rowsecurity) GETSTRUCT(tuple))->rsecrelid; |
||||
|
||||
rel = heap_open(relid, AccessExclusiveLock); |
||||
if (rel->rd_rel->relkind != RELKIND_RELATION) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_WRONG_OBJECT_TYPE), |
||||
errmsg("\"%s\" is not a table", |
||||
RelationGetRelationName(rel)))); |
||||
|
||||
if (!allowSystemTableMods && IsSystemRelation(rel)) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), |
||||
errmsg("permission denied: \"%s\" is a system catalog", |
||||
RelationGetRelationName(rel)))); |
||||
|
||||
simple_heap_delete(pg_rowsecurity_rel, &tuple->t_self); |
||||
|
||||
systable_endscan(sscan); |
||||
heap_close(rel, AccessExclusiveLock); |
||||
|
||||
/*
|
||||
* Note that, unlike some of the other flags in pg_class, relhasrowsecurity |
||||
* is not just an indication of if policies exist. When relhasrowsecurity |
||||
* is set (which can be done directly by the user or indirectly by creating |
||||
* a policy on the table), then all access to the relation must be through |
||||
* a policy. If no policy is defined for the relation then a default-deny |
||||
* policy is created and all records are filtered (except for queries from |
||||
* the owner). |
||||
*/ |
||||
|
||||
CacheInvalidateRelcache(rel); |
||||
|
||||
/* Clean up */ |
||||
heap_close(pg_rowsecurity_rel, RowExclusiveLock); |
||||
} |
||||
|
||||
/*
|
||||
* CreatePolicy - |
||||
* handles the execution of the CREATE POLICY command. |
||||
* |
||||
* stmt - the CreatePolicyStmt that describes the policy to create. |
||||
*/ |
||||
Oid |
||||
CreatePolicy(CreatePolicyStmt *stmt) |
||||
{ |
||||
Relation pg_rowsecurity_rel; |
||||
Oid rowsec_id; |
||||
Relation target_table; |
||||
Oid table_id; |
||||
char rseccmd; |
||||
ArrayType *role_ids; |
||||
ParseState *qual_pstate; |
||||
ParseState *with_check_pstate; |
||||
RangeTblEntry *rte; |
||||
Node *qual; |
||||
Node *with_check_qual; |
||||
ScanKeyData skey[2]; |
||||
SysScanDesc sscan; |
||||
HeapTuple rsec_tuple; |
||||
Datum values[Natts_pg_rowsecurity]; |
||||
bool isnull[Natts_pg_rowsecurity]; |
||||
ObjectAddress target; |
||||
ObjectAddress myself; |
||||
|
||||
/* Parse command */ |
||||
rseccmd = parse_row_security_command(stmt->cmd); |
||||
|
||||
/*
|
||||
* If the command is SELECT or DELETE then WITH CHECK should be NULL. |
||||
*/ |
||||
if ((rseccmd == ACL_SELECT_CHR || rseccmd == ACL_DELETE_CHR) |
||||
&& stmt->with_check != NULL) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_SYNTAX_ERROR), |
||||
errmsg("WITH CHECK cannot be applied to SELECT or DELETE"))); |
||||
|
||||
/*
|
||||
* If the command is INSERT then WITH CHECK should be the only expression |
||||
* provided. |
||||
*/ |
||||
if (rseccmd == ACL_INSERT_CHR && stmt->qual != NULL) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_SYNTAX_ERROR), |
||||
errmsg("Only WITH CHECK expression allowed for INSERT"))); |
||||
|
||||
|
||||
/* Collect role ids */ |
||||
role_ids = rls_role_list_to_array(stmt->roles); |
||||
|
||||
/* Parse the supplied clause */ |
||||
qual_pstate = make_parsestate(NULL); |
||||
with_check_pstate = make_parsestate(NULL); |
||||
|
||||
/* zero-clear */ |
||||
memset(values, 0, sizeof(values)); |
||||
memset(isnull, 0, sizeof(isnull)); |
||||
|
||||
/* Get id of table. Also handles permissions checks. */ |
||||
table_id = RangeVarGetRelidExtended(stmt->table, AccessExclusiveLock, |
||||
false, false, |
||||
RangeVarCallbackForPolicy, |
||||
(void *) stmt); |
||||
|
||||
/* Open target_table to build quals. No lock is necessary.*/ |
||||
target_table = relation_open(table_id, NoLock); |
||||
|
||||
/* Add for the regular security quals */ |
||||
rte = addRangeTableEntryForRelation(qual_pstate, target_table, |
||||
NULL, false, false); |
||||
addRTEtoQuery(qual_pstate, rte, false, true, true); |
||||
|
||||
/* Add for the with-check quals */ |
||||
rte = addRangeTableEntryForRelation(with_check_pstate, target_table, |
||||
NULL, false, false); |
||||
addRTEtoQuery(with_check_pstate, rte, false, true, true); |
||||
|
||||
qual = transformWhereClause(qual_pstate, |
||||
copyObject(stmt->qual), |
||||
EXPR_KIND_WHERE, |
||||
"POLICY"); |
||||
|
||||
with_check_qual = transformWhereClause(with_check_pstate, |
||||
copyObject(stmt->with_check), |
||||
EXPR_KIND_WHERE, |
||||
"POLICY"); |
||||
|
||||
/* Open pg_rowsecurity catalog */ |
||||
pg_rowsecurity_rel = heap_open(RowSecurityRelationId, RowExclusiveLock); |
||||
|
||||
/* Set key - row security relation id. */ |
||||
ScanKeyInit(&skey[0], |
||||
Anum_pg_rowsecurity_rsecrelid, |
||||
BTEqualStrategyNumber, F_OIDEQ, |
||||
ObjectIdGetDatum(table_id)); |
||||
|
||||
/* Set key - row security policy name. */ |
||||
ScanKeyInit(&skey[1], |
||||
Anum_pg_rowsecurity_rsecpolname, |
||||
BTEqualStrategyNumber, F_NAMEEQ, |
||||
CStringGetDatum(stmt->policy_name)); |
||||
|
||||
sscan = systable_beginscan(pg_rowsecurity_rel, |
||||
RowSecurityRelidPolnameIndexId, true, NULL, 2, |
||||
skey); |
||||
|
||||
rsec_tuple = systable_getnext(sscan); |
||||
|
||||
/* Complain if the policy name already exists for the table */ |
||||
if (HeapTupleIsValid(rsec_tuple)) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_DUPLICATE_OBJECT), |
||||
errmsg("policy \"%s\" for relation \"%s\" already exists", |
||||
stmt->policy_name, RelationGetRelationName(target_table)))); |
||||
|
||||
values[Anum_pg_rowsecurity_rsecrelid - 1] = ObjectIdGetDatum(table_id); |
||||
values[Anum_pg_rowsecurity_rsecpolname - 1] |
||||
= CStringGetDatum(stmt->policy_name); |
||||
|
||||
if (rseccmd) |
||||
values[Anum_pg_rowsecurity_rseccmd - 1] = CharGetDatum(rseccmd); |
||||
else |
||||
isnull[Anum_pg_rowsecurity_rseccmd - 1] = true; |
||||
|
||||
values[Anum_pg_rowsecurity_rsecroles - 1] = PointerGetDatum(role_ids); |
||||
|
||||
/* Add qual if present. */ |
||||
if (qual) |
||||
values[Anum_pg_rowsecurity_rsecqual - 1] |
||||
= CStringGetTextDatum(nodeToString(qual)); |
||||
else |
||||
isnull[Anum_pg_rowsecurity_rsecqual - 1] = true; |
||||
|
||||
/* Add WITH CHECK qual if present */ |
||||
if (with_check_qual) |
||||
values[Anum_pg_rowsecurity_rsecwithcheck - 1] |
||||
= CStringGetTextDatum(nodeToString(with_check_qual)); |
||||
else |
||||
isnull[Anum_pg_rowsecurity_rsecwithcheck - 1] = true; |
||||
|
||||
rsec_tuple = heap_form_tuple(RelationGetDescr(pg_rowsecurity_rel), values, |
||||
isnull); |
||||
|
||||
rowsec_id = simple_heap_insert(pg_rowsecurity_rel, rsec_tuple); |
||||
|
||||
/* Update Indexes */ |
||||
CatalogUpdateIndexes(pg_rowsecurity_rel, rsec_tuple); |
||||
|
||||
/* Record Dependencies */ |
||||
target.classId = RelationRelationId; |
||||
target.objectId = table_id; |
||||
target.objectSubId = 0; |
||||
|
||||
myself.classId = RowSecurityRelationId; |
||||
myself.objectId = rowsec_id; |
||||
myself.objectSubId = 0; |
||||
|
||||
recordDependencyOn(&myself, &target, DEPENDENCY_AUTO); |
||||
|
||||
recordDependencyOnExpr(&myself, qual, qual_pstate->p_rtable, |
||||
DEPENDENCY_NORMAL); |
||||
|
||||
recordDependencyOnExpr(&myself, with_check_qual, |
||||
with_check_pstate->p_rtable, DEPENDENCY_NORMAL); |
||||
|
||||
/* Invalidate Relation Cache */ |
||||
CacheInvalidateRelcache(target_table); |
||||
|
||||
/* Clean up. */ |
||||
heap_freetuple(rsec_tuple); |
||||
free_parsestate(qual_pstate); |
||||
free_parsestate(with_check_pstate); |
||||
systable_endscan(sscan); |
||||
relation_close(target_table, NoLock); |
||||
heap_close(pg_rowsecurity_rel, RowExclusiveLock); |
||||
|
||||
return rowsec_id; |
||||
} |
||||
|
||||
/*
|
||||
* AlterPolicy - |
||||
* handles the execution of the ALTER POLICY command. |
||||
* |
||||
* stmt - the AlterPolicyStmt that describes the policy and how to alter it. |
||||
*/ |
||||
Oid |
||||
AlterPolicy(AlterPolicyStmt *stmt) |
||||
{ |
||||
Relation pg_rowsecurity_rel; |
||||
Oid rowsec_id; |
||||
Relation target_table; |
||||
Oid table_id; |
||||
ArrayType *role_ids = NULL; |
||||
List *qual_parse_rtable = NIL; |
||||
List *with_check_parse_rtable = NIL; |
||||
Node *qual = NULL; |
||||
Node *with_check_qual = NULL; |
||||
ScanKeyData skey[2]; |
||||
SysScanDesc sscan; |
||||
HeapTuple rsec_tuple; |
||||
HeapTuple new_tuple; |
||||
Datum values[Natts_pg_rowsecurity]; |
||||
bool isnull[Natts_pg_rowsecurity]; |
||||
bool replaces[Natts_pg_rowsecurity]; |
||||
ObjectAddress target; |
||||
ObjectAddress myself; |
||||
Datum cmd_datum; |
||||
char rseccmd; |
||||
bool rseccmd_isnull; |
||||
|
||||
/* Parse role_ids */ |
||||
if (stmt->roles != NULL) |
||||
role_ids = rls_role_list_to_array(stmt->roles); |
||||
|
||||
/* Get id of table. Also handles permissions checks. */ |
||||
table_id = RangeVarGetRelidExtended(stmt->table, AccessExclusiveLock, |
||||
false, false, |
||||
RangeVarCallbackForPolicy, |
||||
(void *) stmt); |
||||
|
||||
target_table = relation_open(table_id, NoLock); |
||||
|
||||
/* Parse the row-security clause */ |
||||
if (stmt->qual) |
||||
{ |
||||
RangeTblEntry *rte; |
||||
ParseState *qual_pstate = make_parsestate(NULL); |
||||
|
||||
rte = addRangeTableEntryForRelation(qual_pstate, target_table, |
||||
NULL, false, false); |
||||
|
||||
addRTEtoQuery(qual_pstate, rte, false, true, true); |
||||
|
||||
qual = transformWhereClause(qual_pstate, copyObject(stmt->qual), |
||||
EXPR_KIND_WHERE, |
||||
"ROW SECURITY"); |
||||
|
||||
qual_parse_rtable = qual_pstate->p_rtable; |
||||
free_parsestate(qual_pstate); |
||||
} |
||||
|
||||
/* Parse the with-check row-security clause */ |
||||
if (stmt->with_check) |
||||
{ |
||||
RangeTblEntry *rte; |
||||
ParseState *with_check_pstate = make_parsestate(NULL); |
||||
|
||||
rte = addRangeTableEntryForRelation(with_check_pstate, target_table, |
||||
NULL, false, false); |
||||
|
||||
addRTEtoQuery(with_check_pstate, rte, false, true, true); |
||||
|
||||
with_check_qual = transformWhereClause(with_check_pstate, |
||||
copyObject(stmt->with_check), |
||||
EXPR_KIND_WHERE, |
||||
"ROW SECURITY"); |
||||
|
||||
with_check_parse_rtable = with_check_pstate->p_rtable; |
||||
free_parsestate(with_check_pstate); |
||||
} |
||||
|
||||
/* zero-clear */ |
||||
memset(values, 0, sizeof(values)); |
||||
memset(replaces, 0, sizeof(replaces)); |
||||
memset(isnull, 0, sizeof(isnull)); |
||||
|
||||
/* Find policy to update. */ |
||||
pg_rowsecurity_rel = heap_open(RowSecurityRelationId, RowExclusiveLock); |
||||
|
||||
/* Set key - row security relation id. */ |
||||
ScanKeyInit(&skey[0], |
||||
Anum_pg_rowsecurity_rsecrelid, |
||||
BTEqualStrategyNumber, F_OIDEQ, |
||||
ObjectIdGetDatum(table_id)); |
||||
|
||||
/* Set key - row security policy name. */ |
||||
ScanKeyInit(&skey[1], |
||||
Anum_pg_rowsecurity_rsecpolname, |
||||
BTEqualStrategyNumber, F_NAMEEQ, |
||||
CStringGetDatum(stmt->policy_name)); |
||||
|
||||
sscan = systable_beginscan(pg_rowsecurity_rel, |
||||
RowSecurityRelidPolnameIndexId, true, NULL, 2, |
||||
skey); |
||||
|
||||
rsec_tuple = systable_getnext(sscan); |
||||
|
||||
/* Check that the policy is found, raise an error if not. */ |
||||
if (!HeapTupleIsValid(rsec_tuple)) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_UNDEFINED_OBJECT), |
||||
errmsg("policy '%s' for does not exist on table %s", |
||||
stmt->policy_name, |
||||
RelationGetRelationName(target_table)))); |
||||
|
||||
/* Get policy command */ |
||||
cmd_datum = heap_getattr(rsec_tuple, Anum_pg_rowsecurity_rseccmd, |
||||
RelationGetDescr(pg_rowsecurity_rel), |
||||
&rseccmd_isnull); |
||||
if (rseccmd_isnull) |
||||
rseccmd = 0; |
||||
else |
||||
rseccmd = DatumGetChar(cmd_datum); |
||||
|
||||
/*
|
||||
* If the command is SELECT or DELETE then WITH CHECK should be NULL. |
||||
*/ |
||||
if ((rseccmd == ACL_SELECT_CHR || rseccmd == ACL_DELETE_CHR) |
||||
&& stmt->with_check != NULL) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_SYNTAX_ERROR), |
||||
errmsg("only USING expression allowed for SELECT, DELETE"))); |
||||
|
||||
/*
|
||||
* If the command is INSERT then WITH CHECK should be the only |
||||
* expression provided. |
||||
*/ |
||||
if ((rseccmd == ACL_INSERT_CHR) |
||||
&& stmt->qual != NULL) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_SYNTAX_ERROR), |
||||
errmsg("only WITH CHECK expression allowed for INSERT"))); |
||||
|
||||
rowsec_id = HeapTupleGetOid(rsec_tuple); |
||||
|
||||
if (role_ids != NULL) |
||||
{ |
||||
replaces[Anum_pg_rowsecurity_rsecroles - 1] = true; |
||||
values[Anum_pg_rowsecurity_rsecroles - 1] = PointerGetDatum(role_ids); |
||||
} |
||||
|
||||
if (qual != NULL) |
||||
{ |
||||
replaces[Anum_pg_rowsecurity_rsecqual - 1] = true; |
||||
values[Anum_pg_rowsecurity_rsecqual - 1] |
||||
= CStringGetTextDatum(nodeToString(qual)); |
||||
} |
||||
|
||||
if (with_check_qual != NULL) |
||||
{ |
||||
replaces[Anum_pg_rowsecurity_rsecwithcheck - 1] = true; |
||||
values[Anum_pg_rowsecurity_rsecwithcheck - 1] |
||||
= CStringGetTextDatum(nodeToString(with_check_qual)); |
||||
} |
||||
|
||||
new_tuple = heap_modify_tuple(rsec_tuple, |
||||
RelationGetDescr(pg_rowsecurity_rel), |
||||
values, isnull, replaces); |
||||
simple_heap_update(pg_rowsecurity_rel, &new_tuple->t_self, new_tuple); |
||||
|
||||
/* Update Catalog Indexes */ |
||||
CatalogUpdateIndexes(pg_rowsecurity_rel, new_tuple); |
||||
|
||||
/* Update Dependencies. */ |
||||
deleteDependencyRecordsFor(RowSecurityRelationId, rowsec_id, false); |
||||
|
||||
/* Record Dependencies */ |
||||
target.classId = RelationRelationId; |
||||
target.objectId = table_id; |
||||
target.objectSubId = 0; |
||||
|
||||
myself.classId = RowSecurityRelationId; |
||||
myself.objectId = rowsec_id; |
||||
myself.objectSubId = 0; |
||||
|
||||
recordDependencyOn(&myself, &target, DEPENDENCY_AUTO); |
||||
|
||||
recordDependencyOnExpr(&myself, qual, qual_parse_rtable, DEPENDENCY_NORMAL); |
||||
|
||||
recordDependencyOnExpr(&myself, with_check_qual, with_check_parse_rtable, |
||||
DEPENDENCY_NORMAL); |
||||
|
||||
heap_freetuple(new_tuple); |
||||
|
||||
/* Invalidate Relation Cache */ |
||||
CacheInvalidateRelcache(target_table); |
||||
|
||||
/* Clean up. */ |
||||
systable_endscan(sscan); |
||||
relation_close(target_table, NoLock); |
||||
heap_close(pg_rowsecurity_rel, RowExclusiveLock); |
||||
|
||||
return rowsec_id; |
||||
} |
||||
|
||||
/*
|
||||
* rename_policy - |
||||
* change the name of a policy on a relation |
||||
*/ |
||||
Oid |
||||
rename_policy(RenameStmt *stmt) |
||||
{ |
||||
Relation pg_rowsecurity_rel; |
||||
Relation target_table; |
||||
Oid table_id; |
||||
Oid opoloid; |
||||
ScanKeyData skey[2]; |
||||
SysScanDesc sscan; |
||||
HeapTuple rsec_tuple; |
||||
|
||||
/* Get id of table. Also handles permissions checks. */ |
||||
table_id = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock, |
||||
false, false, |
||||
RangeVarCallbackForPolicy, |
||||
(void *) stmt); |
||||
|
||||
target_table = relation_open(table_id, NoLock); |
||||
|
||||
pg_rowsecurity_rel = heap_open(RowSecurityRelationId, RowExclusiveLock); |
||||
|
||||
/* First pass- check for conflict */ |
||||
|
||||
/* Add key - row security relation id. */ |
||||
ScanKeyInit(&skey[0], |
||||
Anum_pg_rowsecurity_rsecrelid, |
||||
BTEqualStrategyNumber, F_OIDEQ, |
||||
ObjectIdGetDatum(table_id)); |
||||
|
||||
/* Add key - row security policy name. */ |
||||
ScanKeyInit(&skey[1], |
||||
Anum_pg_rowsecurity_rsecpolname, |
||||
BTEqualStrategyNumber, F_NAMEEQ, |
||||
CStringGetDatum(stmt->newname)); |
||||
|
||||
sscan = systable_beginscan(pg_rowsecurity_rel, |
||||
RowSecurityRelidPolnameIndexId, true, NULL, 2, |
||||
skey); |
||||
|
||||
if (HeapTupleIsValid(rsec_tuple = systable_getnext(sscan))) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_DUPLICATE_OBJECT), |
||||
errmsg("row-policy \"%s\" for table \"%s\" already exists", |
||||
stmt->newname, RelationGetRelationName(target_table)))); |
||||
|
||||
systable_endscan(sscan); |
||||
|
||||
/* Second pass -- find existing policy and update */ |
||||
/* Add key - row security relation id. */ |
||||
ScanKeyInit(&skey[0], |
||||
Anum_pg_rowsecurity_rsecrelid, |
||||
BTEqualStrategyNumber, F_OIDEQ, |
||||
ObjectIdGetDatum(table_id)); |
||||
|
||||
/* Add key - row security policy name. */ |
||||
ScanKeyInit(&skey[1], |
||||
Anum_pg_rowsecurity_rsecpolname, |
||||
BTEqualStrategyNumber, F_NAMEEQ, |
||||
CStringGetDatum(stmt->subname)); |
||||
|
||||
sscan = systable_beginscan(pg_rowsecurity_rel, |
||||
RowSecurityRelidPolnameIndexId, true, NULL, 2, |
||||
skey); |
||||
|
||||
rsec_tuple = systable_getnext(sscan); |
||||
|
||||
/* Complain if we did not find the policy */ |
||||
if (!HeapTupleIsValid(rsec_tuple)) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_UNDEFINED_OBJECT), |
||||
errmsg("row-policy \"%s\" for table \"%s\" does not exist", |
||||
stmt->subname, RelationGetRelationName(target_table)))); |
||||
|
||||
opoloid = HeapTupleGetOid(rsec_tuple); |
||||
|
||||
rsec_tuple = heap_copytuple(rsec_tuple); |
||||
|
||||
namestrcpy(&((Form_pg_rowsecurity) GETSTRUCT(rsec_tuple))->rsecpolname, |
||||
stmt->newname); |
||||
|
||||
simple_heap_update(pg_rowsecurity_rel, &rsec_tuple->t_self, rsec_tuple); |
||||
|
||||
/* keep system catalog indexes current */ |
||||
CatalogUpdateIndexes(pg_rowsecurity_rel, rsec_tuple); |
||||
|
||||
InvokeObjectPostAlterHook(RowSecurityRelationId, |
||||
HeapTupleGetOid(rsec_tuple), 0); |
||||
|
||||
/*
|
||||
* Invalidate relation's relcache entry so that other backends (and |
||||
* this one too!) are sent SI message to make them rebuild relcache |
||||
* entries. (Ideally this should happen automatically...) |
||||
*/ |
||||
CacheInvalidateRelcache(target_table); |
||||
|
||||
/* Clean up. */ |
||||
systable_endscan(sscan); |
||||
heap_close(pg_rowsecurity_rel, RowExclusiveLock); |
||||
relation_close(target_table, NoLock); |
||||
|
||||
return opoloid; |
||||
} |
||||
|
||||
/*
|
||||
* get_relation_policy_oid - Look up a policy by name to find its OID |
||||
* |
||||
* If missing_ok is false, throw an error if policy not found. If |
||||
* true, just return InvalidOid. |
||||
*/ |
||||
Oid |
||||
get_relation_policy_oid(Oid relid, const char *policy_name, bool missing_ok) |
||||
{ |
||||
Relation pg_rowsecurity_rel; |
||||
ScanKeyData skey[2]; |
||||
SysScanDesc sscan; |
||||
HeapTuple rsec_tuple; |
||||
Oid policy_oid; |
||||
|
||||
pg_rowsecurity_rel = heap_open(RowSecurityRelationId, AccessShareLock); |
||||
|
||||
/* Add key - row security relation id. */ |
||||
ScanKeyInit(&skey[0], |
||||
Anum_pg_rowsecurity_rsecrelid, |
||||
BTEqualStrategyNumber, F_OIDEQ, |
||||
ObjectIdGetDatum(relid)); |
||||
|
||||
/* Add key - row security policy name. */ |
||||
ScanKeyInit(&skey[1], |
||||
Anum_pg_rowsecurity_rsecpolname, |
||||
BTEqualStrategyNumber, F_NAMEEQ, |
||||
CStringGetDatum(policy_name)); |
||||
|
||||
sscan = systable_beginscan(pg_rowsecurity_rel, |
||||
RowSecurityRelidPolnameIndexId, true, NULL, 2, |
||||
skey); |
||||
|
||||
rsec_tuple = systable_getnext(sscan); |
||||
|
||||
if (!HeapTupleIsValid(rsec_tuple)) |
||||
{ |
||||
if (!missing_ok) |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_UNDEFINED_OBJECT), |
||||
errmsg("policy \"%s\" for table \"%s\" does not exist", |
||||
policy_name, get_rel_name(relid)))); |
||||
|
||||
policy_oid = InvalidOid; |
||||
} |
||||
else |
||||
policy_oid = HeapTupleGetOid(rsec_tuple); |
||||
|
||||
/* Clean up. */ |
||||
systable_endscan(sscan); |
||||
heap_close(pg_rowsecurity_rel, AccessShareLock); |
||||
|
||||
return policy_oid; |
||||
} |
||||
@ -0,0 +1,557 @@ |
||||
/*
|
||||
* rewrite/rowsecurity.c |
||||
* Routines to support policies for row-level security. |
||||
* |
||||
* Policies in PostgreSQL provide a mechanism to limit what records are |
||||
* returned to a user and what records a user is permitted to add to a table. |
||||
* |
||||
* Policies can be defined for specific roles, specific commands, or provided |
||||
* by an extension. Row security can also be enabled for a table without any |
||||
* policies being explicitly defined, in which case a default-deny policy is |
||||
* applied. |
||||
* |
||||
* Any part of the system which is returning records back to the user, or |
||||
* which is accepting records from the user to add to a table, needs to |
||||
* consider the policies associated with the table (if any). For normal |
||||
* queries, this is handled by calling prepend_row_security_policies() during |
||||
* rewrite, which looks at each RTE and adds the expressions defined by the |
||||
* policies to the securityQuals list for the RTE. For queries which modify |
||||
* the relation, any WITH CHECK policies are added to the list of |
||||
* WithCheckOptions for the Query and checked against each row which is being |
||||
* added to the table. Other parts of the system (eg: COPY) simply construct |
||||
* a normal query and use that, if RLS is to be applied. |
||||
* |
||||
* The check to see if RLS should be enabled is provided through |
||||
* check_enable_rls(), which returns an enum (defined in rowsecurity.h) to |
||||
* indicate if RLS should be enabled (RLS_ENABLED), or bypassed (RLS_NONE or |
||||
* RLS_NONE_ENV). RLS_NONE_ENV indicates that RLS should be bypassed |
||||
* in the current environment, but that may change if the row_security GUC or |
||||
* the current role changes. |
||||
* |
||||
* Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
*/ |
||||
#include "postgres.h" |
||||
|
||||
#include "access/heapam.h" |
||||
#include "access/htup_details.h" |
||||
#include "access/sysattr.h" |
||||
#include "catalog/pg_class.h" |
||||
#include "catalog/pg_inherits_fn.h" |
||||
#include "catalog/pg_rowsecurity.h" |
||||
#include "catalog/pg_type.h" |
||||
#include "miscadmin.h" |
||||
#include "nodes/makefuncs.h" |
||||
#include "nodes/nodeFuncs.h" |
||||
#include "nodes/pg_list.h" |
||||
#include "nodes/plannodes.h" |
||||
#include "parser/parsetree.h" |
||||
#include "rewrite/rewriteHandler.h" |
||||
#include "rewrite/rewriteManip.h" |
||||
#include "rewrite/rowsecurity.h" |
||||
#include "utils/acl.h" |
||||
#include "utils/lsyscache.h" |
||||
#include "utils/rel.h" |
||||
#include "utils/syscache.h" |
||||
#include "tcop/utility.h" |
||||
|
||||
static List *pull_row_security_policies(CmdType cmd, Relation relation, |
||||
Oid user_id); |
||||
static void process_policies(List *policies, int rt_index, |
||||
Expr **final_qual, |
||||
Expr **final_with_check_qual, |
||||
bool *hassublinks); |
||||
static bool check_role_for_policy(RowSecurityPolicy *policy, Oid user_id); |
||||
|
||||
/*
|
||||
* hook to allow extensions to apply their own security policy |
||||
* |
||||
* See below where the hook is called in prepend_row_security_policies for |
||||
* insight into how to use this hook. |
||||
*/ |
||||
row_security_policy_hook_type row_security_policy_hook = NULL; |
||||
|
||||
/*
|
||||
* Check the given RTE to see whether it's already had row-security quals |
||||
* expanded and, if not, prepend any row-security rules from built-in or |
||||
* plug-in sources to the securityQuals. The security quals are rewritten (for |
||||
* view expansion, etc) before being added to the RTE. |
||||
* |
||||
* Returns true if any quals were added. Note that quals may have been found |
||||
* but not added if user rights make the user exempt from row security. |
||||
*/ |
||||
bool |
||||
prepend_row_security_policies(Query* root, RangeTblEntry* rte, int rt_index) |
||||
{ |
||||
Expr *rowsec_expr = NULL; |
||||
Expr *rowsec_with_check_expr = NULL; |
||||
Expr *hook_expr = NULL; |
||||
Expr *hook_with_check_expr = NULL; |
||||
|
||||
List *rowsec_policies; |
||||
List *hook_policies = NIL; |
||||
|
||||
Relation rel; |
||||
Oid user_id; |
||||
int sec_context; |
||||
int rls_status; |
||||
bool defaultDeny = true; |
||||
bool hassublinks = false; |
||||
|
||||
/* This is just to get the security context */ |
||||
GetUserIdAndSecContext(&user_id, &sec_context); |
||||
|
||||
/* Switch to checkAsUser if it's set */ |
||||
user_id = rte->checkAsUser ? rte->checkAsUser : GetUserId(); |
||||
|
||||
/*
|
||||
* If this is not a normal relation, or we have been told |
||||
* to explicitly skip RLS (perhaps because this is an FK check) |
||||
* then just return immediately. |
||||
*/ |
||||
if (rte->relid < FirstNormalObjectId |
||||
|| rte->relkind != RELKIND_RELATION |
||||
|| (sec_context & SECURITY_ROW_LEVEL_DISABLED)) |
||||
return false; |
||||
|
||||
/* Determine the state of RLS for this, pass checkAsUser explicitly */ |
||||
rls_status = check_enable_rls(rte->relid, rte->checkAsUser); |
||||
|
||||
/* If there is no RLS on this table at all, nothing to do */ |
||||
if (rls_status == RLS_NONE) |
||||
return false; |
||||
|
||||
/*
|
||||
* RLS_NONE_ENV means we are not doing any RLS now, but that may change |
||||
* with changes to the environment, so we mark it as hasRowSecurity to |
||||
* force a re-plan when the environment changes. |
||||
*/ |
||||
if (rls_status == RLS_NONE_ENV) |
||||
{ |
||||
/*
|
||||
* Indicate that this query may involve RLS and must therefore |
||||
* be replanned if the environment changes (GUCs, role), but we |
||||
* are not adding anything here. |
||||
*/ |
||||
root->hasRowSecurity = true; |
||||
|
||||
return false; |
||||
} |
||||
|
||||
/*
|
||||
* We may end up getting called multiple times for the same RTE, so check |
||||
* to make sure we aren't doing double-work. |
||||
*/ |
||||
if (rte->securityQuals != NIL) |
||||
return false; |
||||
|
||||
/* Grab the built-in policies which should be applied to this relation. */ |
||||
rel = heap_open(rte->relid, NoLock); |
||||
|
||||
rowsec_policies = pull_row_security_policies(root->commandType, rel, |
||||
user_id); |
||||
|
||||
/*
|
||||
* Check if this is only the default-deny policy. |
||||
* |
||||
* Normally, if the table has row-security enabled but there are |
||||
* no policies, we use a default-deny policy and not allow anything. |
||||
* However, when an extension uses the hook to add their own |
||||
* policies, we don't want to include the default deny policy or |
||||
* there won't be any way for a user to use an extension exclusively |
||||
* for the policies to be used. |
||||
*/ |
||||
if (((RowSecurityPolicy *) linitial(rowsec_policies))->rsecid |
||||
== InvalidOid) |
||||
defaultDeny = true; |
||||
|
||||
/* Now that we have our policies, build the expressions from them. */ |
||||
process_policies(rowsec_policies, rt_index, &rowsec_expr, |
||||
&rowsec_with_check_expr, &hassublinks); |
||||
|
||||
/*
|
||||
* Also, allow extensions to add their own policies. |
||||
* |
||||
* Note that, as with the internal policies, if multiple policies are |
||||
* returned then they will be combined into a single expression with |
||||
* all of them OR'd together. However, to avoid the situation of an |
||||
* extension granting more access to a table than the internal policies |
||||
* would allow, the extension's policies are AND'd with the internal |
||||
* policies. In other words- extensions can only provide further |
||||
* filtering of the result set (or further reduce the set of records |
||||
* allowed to be added). |
||||
* |
||||
* If only a USING policy is returned by the extension then it will be |
||||
* used for WITH CHECK as well, similar to how internal policies are |
||||
* handled. |
||||
* |
||||
* The only caveat to this is that if there are NO internal policies |
||||
* defined, there ARE policies returned by the extension, and RLS is |
||||
* enabled on the table, then we will ignore the internally-generated |
||||
* default-deny policy and use only the policies returned by the |
||||
* extension. |
||||
*/ |
||||
if (row_security_policy_hook) |
||||
{ |
||||
hook_policies = (*row_security_policy_hook)(root->commandType, rel); |
||||
|
||||
/* Build the expression from any policies returned. */ |
||||
process_policies(hook_policies, rt_index, &hook_expr, |
||||
&hook_with_check_expr, &hassublinks); |
||||
} |
||||
|
||||
/*
|
||||
* If the only built-in policy is the default-deny one, and hook |
||||
* policies exist, then use the hook policies only and do not apply |
||||
* the default-deny policy. Otherwise, apply both sets (AND'd |
||||
* together). |
||||
*/ |
||||
if (defaultDeny && hook_policies != NIL) |
||||
rowsec_expr = NULL; |
||||
|
||||
/*
|
||||
* For INSERT or UPDATE, we need to add the WITH CHECK quals to |
||||
* Query's withCheckOptions to verify that any new records pass the |
||||
* WITH CHECK policy (this will be a copy of the USING policy, if no |
||||
* explicit WITH CHECK policy exists). |
||||
*/ |
||||
if (root->commandType == CMD_INSERT || root->commandType == CMD_UPDATE) |
||||
{ |
||||
/*
|
||||
* WITH CHECK OPTIONS wants a WCO node which wraps each Expr, so |
||||
* create them as necessary. |
||||
*/ |
||||
if (rowsec_with_check_expr) |
||||
{ |
||||
WithCheckOption *wco; |
||||
|
||||
wco = (WithCheckOption *) makeNode(WithCheckOption); |
||||
wco->viewname = RelationGetRelationName(rel); |
||||
wco->qual = (Node *) rowsec_with_check_expr; |
||||
wco->cascaded = false; |
||||
root->withCheckOptions = lcons(wco, root->withCheckOptions); |
||||
} |
||||
|
||||
/*
|
||||
* Ditto for the expression, if any, returned from the extension. |
||||
*/ |
||||
if (hook_with_check_expr) |
||||
{ |
||||
WithCheckOption *wco; |
||||
|
||||
wco = (WithCheckOption *) makeNode(WithCheckOption); |
||||
wco->viewname = RelationGetRelationName(rel); |
||||
wco->qual = (Node *) hook_with_check_expr; |
||||
wco->cascaded = false; |
||||
root->withCheckOptions = lcons(wco, root->withCheckOptions); |
||||
} |
||||
} |
||||
|
||||
/* For SELECT, UPDATE, and DELETE, set the security quals */ |
||||
if (root->commandType == CMD_SELECT |
||||
|| root->commandType == CMD_UPDATE |
||||
|| root->commandType == CMD_DELETE) |
||||
{ |
||||
if (rowsec_expr) |
||||
rte->securityQuals = lcons(rowsec_expr, rte->securityQuals); |
||||
|
||||
if (hook_expr) |
||||
rte->securityQuals = lcons(hook_expr, |
||||
rte->securityQuals); |
||||
} |
||||
|
||||
heap_close(rel, NoLock); |
||||
|
||||
/*
|
||||
* Mark this query as having row security, so plancache can invalidate |
||||
* it when necessary (eg: role changes) |
||||
*/ |
||||
root->hasRowSecurity = true; |
||||
|
||||
/*
|
||||
* If we have sublinks added because of the policies being added to the |
||||
* query, then set hasSubLinks on the Query to force subLinks to be |
||||
* properly expanded. |
||||
*/ |
||||
if (hassublinks) |
||||
root->hasSubLinks = hassublinks; |
||||
|
||||
/* If we got this far, we must have added quals */ |
||||
return true; |
||||
} |
||||
|
||||
/*
|
||||
* pull_row_security_policies |
||||
* |
||||
* Returns the list of policies to be added for this relation, based on the |
||||
* type of command and the roles to which it applies, from the relation cache. |
||||
* |
||||
*/ |
||||
static List * |
||||
pull_row_security_policies(CmdType cmd, Relation relation, Oid user_id) |
||||
{ |
||||
List *policies = NIL; |
||||
ListCell *item; |
||||
RowSecurityPolicy *policy; |
||||
|
||||
/*
|
||||
* Row security is enabled for the relation and the row security GUC is |
||||
* either 'on' or 'force' here, so find the policies to apply to the table. |
||||
* There must always be at least one policy defined (may be the simple |
||||
* 'default-deny' policy, if none are explicitly defined on the table). |
||||
*/ |
||||
foreach(item, relation->rsdesc->policies) |
||||
{ |
||||
policy = (RowSecurityPolicy *) lfirst(item); |
||||
|
||||
/* Always add ALL policies, if they exist. */ |
||||
if (policy->cmd == '\0' && check_role_for_policy(policy, user_id)) |
||||
policies = lcons(policy, policies); |
||||
|
||||
/* Build the list of policies to return. */ |
||||
switch(cmd) |
||||
{ |
||||
case CMD_SELECT: |
||||
if (policy->cmd == ACL_SELECT_CHR |
||||
&& check_role_for_policy(policy, user_id)) |
||||
policies = lcons(policy, policies); |
||||
break; |
||||
case CMD_INSERT: |
||||
/* If INSERT then only need to add the WITH CHECK qual */ |
||||
if (policy->cmd == ACL_INSERT_CHR |
||||
&& check_role_for_policy(policy, user_id)) |
||||
policies = lcons(policy, policies); |
||||
break; |
||||
case CMD_UPDATE: |
||||
if (policy->cmd == ACL_UPDATE_CHR |
||||
&& check_role_for_policy(policy, user_id)) |
||||
policies = lcons(policy, policies); |
||||
break; |
||||
case CMD_DELETE: |
||||
if (policy->cmd == ACL_DELETE_CHR |
||||
&& check_role_for_policy(policy, user_id)) |
||||
policies = lcons(policy, policies); |
||||
break; |
||||
default: |
||||
elog(ERROR, "unrecognized command type."); |
||||
break; |
||||
} |
||||
} |
||||
|
||||
/*
|
||||
* There should always be a policy applied. If there are none found then |
||||
* create a simply defauly-deny policy (might be that policies exist but |
||||
* that none of them apply to the role which is querying the table). |
||||
*/ |
||||
if (policies == NIL) |
||||
{ |
||||
RowSecurityPolicy *policy = NULL; |
||||
Datum role; |
||||
|
||||
role = ObjectIdGetDatum(ACL_ID_PUBLIC); |
||||
|
||||
policy = palloc0(sizeof(RowSecurityPolicy)); |
||||
policy->policy_name = pstrdup("default-deny policy"); |
||||
policy->rsecid = InvalidOid; |
||||
policy->cmd = '\0'; |
||||
policy->roles = construct_array(&role, 1, OIDOID, sizeof(Oid), true, |
||||
'i'); |
||||
policy->qual = (Expr *) makeConst(BOOLOID, -1, InvalidOid, |
||||
sizeof(bool), BoolGetDatum(false), |
||||
false, true); |
||||
policy->with_check_qual = copyObject(policy->qual); |
||||
policy->hassublinks = false; |
||||
|
||||
policies = list_make1(policy); |
||||
} |
||||
|
||||
Assert(policies != NIL); |
||||
|
||||
return policies; |
||||
} |
||||
|
||||
/*
|
||||
* process_policies |
||||
* |
||||
* This will step through the policies which are passed in (which would come |
||||
* from either the built-in ones created on a table, or from policies provided |
||||
* by an extension through the hook provided), work out how to combine them, |
||||
* rewrite them as necessary, and produce an Expr for the normal security |
||||
* quals and an Expr for the with check quals. |
||||
* |
||||
* qual_eval, with_check_eval, and hassublinks are output variables |
||||
*/ |
||||
static void |
||||
process_policies(List *policies, int rt_index, Expr **qual_eval, |
||||
Expr **with_check_eval, bool *hassublinks) |
||||
{ |
||||
ListCell *item; |
||||
List *quals = NIL; |
||||
List *with_check_quals = NIL; |
||||
|
||||
/*
|
||||
* Extract the USING and WITH CHECK quals from each of the policies |
||||
* and add them to our lists. |
||||
*/ |
||||
foreach(item, policies) |
||||
{ |
||||
RowSecurityPolicy *policy = (RowSecurityPolicy *) lfirst(item); |
||||
|
||||
if (policy->qual != NULL) |
||||
quals = lcons(copyObject(policy->qual), quals); |
||||
|
||||
if (policy->with_check_qual != NULL) |
||||
with_check_quals = lcons(copyObject(policy->with_check_qual), |
||||
with_check_quals); |
||||
|
||||
if (policy->hassublinks) |
||||
*hassublinks = true; |
||||
} |
||||
|
||||
/*
|
||||
* If we end up without any normal quals (perhaps the only policy matched |
||||
* was for INSERT), then create a single all-false one. |
||||
*/ |
||||
if (quals == NIL) |
||||
quals = lcons(makeConst(BOOLOID, -1, InvalidOid, sizeof(bool), |
||||
BoolGetDatum(false), false, true), quals); |
||||
|
||||
/*
|
||||
* If we end up with only USING quals, then use those as |
||||
* WITH CHECK quals also. |
||||
*/ |
||||
if (with_check_quals == NIL) |
||||
with_check_quals = copyObject(quals); |
||||
|
||||
/*
|
||||
* Row security quals always have the target table as varno 1, as no |
||||
* joins are permitted in row security expressions. We must walk the |
||||
* expression, updating any references to varno 1 to the varno |
||||
* the table has in the outer query. |
||||
* |
||||
* We rewrite the expression in-place. |
||||
*/ |
||||
ChangeVarNodes((Node *) quals, 1, rt_index, 0); |
||||
ChangeVarNodes((Node *) with_check_quals, 1, rt_index, 0); |
||||
|
||||
/*
|
||||
* If more than one security qual is returned, then they need to be |
||||
* OR'ed together. |
||||
*/ |
||||
if (list_length(quals) > 1) |
||||
*qual_eval = makeBoolExpr(OR_EXPR, quals, -1); |
||||
else |
||||
*qual_eval = (Expr*) linitial(quals); |
||||
|
||||
/*
|
||||
* If more than one WITH CHECK qual is returned, then they need to |
||||
* be OR'ed together. |
||||
*/ |
||||
if (list_length(with_check_quals) > 1) |
||||
*with_check_eval = makeBoolExpr(OR_EXPR, with_check_quals, -1); |
||||
else |
||||
*with_check_eval = (Expr*) linitial(with_check_quals); |
||||
|
||||
return; |
||||
} |
||||
|
||||
/*
|
||||
* check_enable_rls |
||||
* |
||||
* Determine, based on the relation, row_security setting, and current role, |
||||
* if RLS is applicable to this query. RLS_NONE_ENV indicates that, while |
||||
* RLS is not to be added for this query, a change in the environment may change |
||||
* that. RLS_NONE means that RLS is not on the relation at all and therefore |
||||
* we don't need to worry about it. RLS_ENABLED means RLS should be implemented |
||||
* for the table and the plan cache needs to be invalidated if the environment |
||||
* changes. |
||||
* |
||||
* Handle checking as another role via checkAsUser (for views, etc). |
||||
*/ |
||||
int |
||||
check_enable_rls(Oid relid, Oid checkAsUser) |
||||
{ |
||||
HeapTuple tuple; |
||||
Form_pg_class classform; |
||||
bool relhasrowsecurity; |
||||
Oid user_id = checkAsUser ? checkAsUser : GetUserId(); |
||||
|
||||
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid)); |
||||
if (!HeapTupleIsValid(tuple)) |
||||
return RLS_NONE; |
||||
|
||||
classform = (Form_pg_class) GETSTRUCT(tuple); |
||||
|
||||
relhasrowsecurity = classform->relhasrowsecurity; |
||||
|
||||
ReleaseSysCache(tuple); |
||||
|
||||
/* Nothing to do if the relation does not have RLS */ |
||||
if (!relhasrowsecurity) |
||||
return RLS_NONE; |
||||
|
||||
/*
|
||||
* Check permissions |
||||
* |
||||
* If the relation has row level security enabled and the row_security GUC |
||||
* is off, then check if the user has rights to bypass RLS for this |
||||
* relation. Table owners can always bypass, as can any role with the |
||||
* BYPASSRLS capability. |
||||
* |
||||
* If the role is the table owner, then we bypass RLS unless row_security |
||||
* is set to 'force'. Note that superuser is always considered an owner. |
||||
* |
||||
* Return RLS_NONE_ENV to indicate that this decision depends on the |
||||
* environment (in this case, what the current values of user_id and |
||||
* row_security are). |
||||
*/ |
||||
if (row_security != ROW_SECURITY_FORCE |
||||
&& (pg_class_ownercheck(relid, user_id))) |
||||
return RLS_NONE_ENV; |
||||
|
||||
/*
|
||||
* If the row_security GUC is 'off' then check if the user has permission |
||||
* to bypass it. Note that we have already handled the case where the user |
||||
* is the table owner above. |
||||
* |
||||
* Note that row_security is always considered 'on' when querying |
||||
* through a view or other cases where checkAsUser is true, so skip this |
||||
* if checkAsUser is in use. |
||||
*/ |
||||
if (!checkAsUser && row_security == ROW_SECURITY_OFF) |
||||
{ |
||||
if (has_bypassrls_privilege(user_id)) |
||||
/* OK to bypass */ |
||||
return RLS_NONE_ENV; |
||||
else |
||||
ereport(ERROR, |
||||
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), |
||||
errmsg("insufficient privilege to bypass row security."))); |
||||
} |
||||
|
||||
/* RLS should be fully enabled for this relation. */ |
||||
return RLS_ENABLED; |
||||
} |
||||
|
||||
/*
|
||||
* check_role_for_policy - |
||||
* determines if the policy should be applied for the current role |
||||
*/ |
||||
bool |
||||
check_role_for_policy(RowSecurityPolicy *policy, Oid user_id) |
||||
{ |
||||
int i; |
||||
Oid *roles = (Oid *) ARR_DATA_PTR(policy->roles); |
||||
|
||||
/* Quick fall-thru for policies applied to all roles */ |
||||
if (roles[0] == ACL_ID_PUBLIC) |
||||
return true; |
||||
|
||||
for (i = 0; i < ARR_DIMS(policy->roles)[0]; i++) |
||||
{ |
||||
if (is_member_of_role(user_id, roles[i])) |
||||
return true; |
||||
} |
||||
|
||||
return false; |
||||
} |
||||
@ -0,0 +1,53 @@ |
||||
/*
|
||||
* pg_rowsecurity.h |
||||
* definition of the system catalog for row-security policy (pg_rowsecurity) |
||||
* |
||||
* Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
* |
||||
*/ |
||||
#ifndef PG_ROWSECURITY_H |
||||
#define PG_ROWSECURITY_H |
||||
|
||||
#include "catalog/genbki.h" |
||||
|
||||
/* ----------------
|
||||
* pg_rowsecurity definition. cpp turns this into |
||||
* typedef struct FormData_pg_rowsecurity |
||||
* ---------------- |
||||
*/ |
||||
#define RowSecurityRelationId 3256 |
||||
|
||||
CATALOG(pg_rowsecurity,3256) |
||||
{ |
||||
NameData rsecpolname; /* Policy name. */ |
||||
Oid rsecrelid; /* Oid of the relation with policy. */ |
||||
char rseccmd; /* One of ACL_*_CHR, or \0 for all */ |
||||
|
||||
#ifdef CATALOG_VARLEN |
||||
Oid rsecroles[1] /* Roles associated with policy, not-NULL */ |
||||
pg_node_tree rsecqual; /* Policy quals. */ |
||||
pg_node_tree rsecwithcheck; /* WITH CHECK quals. */ |
||||
#endif |
||||
} FormData_pg_rowsecurity; |
||||
|
||||
/* ----------------
|
||||
* Form_pg_rowsecurity corresponds to a pointer to a row with |
||||
* the format of pg_rowsecurity relation. |
||||
* ---------------- |
||||
*/ |
||||
typedef FormData_pg_rowsecurity *Form_pg_rowsecurity; |
||||
|
||||
/* ----------------
|
||||
* compiler constants for pg_rowsecurity |
||||
* ---------------- |
||||
*/ |
||||
#define Natts_pg_rowsecurity 6 |
||||
#define Anum_pg_rowsecurity_rsecpolname 1 |
||||
#define Anum_pg_rowsecurity_rsecrelid 2 |
||||
#define Anum_pg_rowsecurity_rseccmd 3 |
||||
#define Anum_pg_rowsecurity_rsecroles 4 |
||||
#define Anum_pg_rowsecurity_rsecqual 5 |
||||
#define Anum_pg_rowsecurity_rsecwithcheck 6 |
||||
|
||||
#endif /* PG_ROWSECURITY_H */ |
||||
@ -0,0 +1,33 @@ |
||||
/*-------------------------------------------------------------------------
|
||||
* |
||||
* policy.h |
||||
* prototypes for policy.c. |
||||
* |
||||
* |
||||
* Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
* |
||||
* src/include/commands/policy.h |
||||
* |
||||
*------------------------------------------------------------------------- |
||||
*/ |
||||
|
||||
#ifndef POLICY_H |
||||
#define POLICY_H |
||||
|
||||
#include "nodes/parsenodes.h" |
||||
|
||||
extern void RelationBuildRowSecurity(Relation relation); |
||||
|
||||
extern void RemovePolicyById(Oid policy_id); |
||||
|
||||
extern Oid CreatePolicy(CreatePolicyStmt *stmt); |
||||
extern Oid AlterPolicy(AlterPolicyStmt *stmt); |
||||
|
||||
Oid get_relation_policy_oid(Oid relid, |
||||
const char *policy_name, bool missing_ok); |
||||
|
||||
Oid rename_policy(RenameStmt *stmt); |
||||
|
||||
|
||||
#endif /* POLICY_H */ |
||||
@ -0,0 +1,80 @@ |
||||
/* -------------------------------------------------------------------------
|
||||
* |
||||
* rowsecurity.h |
||||
* prototypes for optimizer/rowsecurity.c |
||||
* |
||||
* Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group |
||||
* Portions Copyright (c) 1994, Regents of the University of California |
||||
* |
||||
* ------------------------------------------------------------------------- |
||||
*/ |
||||
#ifndef ROWSECURITY_H |
||||
#define ROWSECURITY_H |
||||
|
||||
#include "nodes/execnodes.h" |
||||
#include "nodes/parsenodes.h" |
||||
#include "nodes/relation.h" |
||||
#include "utils/array.h" |
||||
|
||||
typedef struct RowSecurityPolicy |
||||
{ |
||||
Oid rsecid; |
||||
char *policy_name; |
||||
char cmd; |
||||
ArrayType *roles; |
||||
Expr *qual; |
||||
Expr *with_check_qual; |
||||
bool hassublinks; |
||||
} RowSecurityPolicy; |
||||
|
||||
typedef struct RowSecurityDesc |
||||
{ |
||||
MemoryContext rscxt; /* row-security memory context */ |
||||
List *policies; /* list of row-security policies */ |
||||
} RowSecurityDesc; |
||||
|
||||
/* GUC variable */ |
||||
extern int row_security; |
||||
|
||||
/* Possible values for row_security GUC */ |
||||
typedef enum RowSecurityConfigType |
||||
{ |
||||
ROW_SECURITY_OFF, |
||||
ROW_SECURITY_ON, |
||||
ROW_SECURITY_FORCE |
||||
} RowSecurityConfigType; |
||||
|
||||
/*
|
||||
* Used by callers of check_enable_rls. |
||||
* |
||||
* RLS could be completely disabled on the tables involved in the query, |
||||
* which is the simple case, or it may depend on the current environment |
||||
* (the role which is running the query or the value of the row_security |
||||
* GUC- on, off, or force), or it might be simply enabled as usual. |
||||
* |
||||
* If RLS isn't on the table involved then RLS_NONE is returned to indicate |
||||
* that we don't need to worry about invalidating the query plan for RLS |
||||
* reasons. If RLS is on the table, but we are bypassing it for now, then |
||||
* we return RLS_NONE_ENV to indicate that, if the environment changes, |
||||
* we need to invalidate and replan. Finally, if RLS should be turned on |
||||
* for the query, then we return RLS_ENABLED, which means we also need to |
||||
* invalidate if the environment changes. |
||||
*/ |
||||
enum CheckEnableRlsResult |
||||
{ |
||||
RLS_NONE, |
||||
RLS_NONE_ENV, |
||||
RLS_ENABLED |
||||
}; |
||||
|
||||
typedef List *(*row_security_policy_hook_type)(CmdType cmdtype, |
||||
Relation relation); |
||||
|
||||
extern PGDLLIMPORT row_security_policy_hook_type row_security_policy_hook; |
||||
|
||||
extern bool prepend_row_security_policies(Query* root, RangeTblEntry* rte, |
||||
int rt_index); |
||||
|
||||
extern int check_enable_rls(Oid relid, Oid checkAsUser); |
||||
|
||||
#endif /* ROWSECURITY_H */ |
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,921 @@ |
||||
-- |
||||
-- Test of Row-level security feature |
||||
-- |
||||
|
||||
-- Clean up in case a prior regression run failed |
||||
|
||||
-- Suppress NOTICE messages when users/groups don't exist |
||||
SET client_min_messages TO 'warning'; |
||||
|
||||
DROP USER IF EXISTS rls_regress_user0; |
||||
DROP USER IF EXISTS rls_regress_user1; |
||||
DROP USER IF EXISTS rls_regress_user2; |
||||
DROP USER IF EXISTS rls_regress_exempt_user; |
||||
DROP ROLE IF EXISTS rls_regress_group1; |
||||
DROP ROLE IF EXISTS rls_regress_group2; |
||||
|
||||
DROP SCHEMA IF EXISTS rls_regress_schema CASCADE; |
||||
|
||||
RESET client_min_messages; |
||||
|
||||
-- initial setup |
||||
CREATE USER rls_regress_user0; |
||||
CREATE USER rls_regress_user1; |
||||
CREATE USER rls_regress_user2; |
||||
CREATE USER rls_regress_exempt_user BYPASSRLS; |
||||
CREATE ROLE rls_regress_group1 NOLOGIN; |
||||
CREATE ROLE rls_regress_group2 NOLOGIN; |
||||
|
||||
GRANT rls_regress_group1 TO rls_regress_user1; |
||||
GRANT rls_regress_group2 TO rls_regress_user2; |
||||
|
||||
CREATE SCHEMA rls_regress_schema; |
||||
GRANT ALL ON SCHEMA rls_regress_schema to public; |
||||
SET search_path = rls_regress_schema; |
||||
|
||||
-- setup of malicious function |
||||
CREATE OR REPLACE FUNCTION f_leak(text) RETURNS bool |
||||
COST 0.0000001 LANGUAGE plpgsql |
||||
AS 'BEGIN RAISE NOTICE ''f_leak => %'', $1; RETURN true; END'; |
||||
GRANT EXECUTE ON FUNCTION f_leak(text) TO public; |
||||
|
||||
-- BASIC Row-Level Security Scenario |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
CREATE TABLE uaccount ( |
||||
pguser name primary key, |
||||
seclv int |
||||
); |
||||
GRANT SELECT ON uaccount TO public; |
||||
INSERT INTO uaccount VALUES |
||||
('rls_regress_user0', 99), |
||||
('rls_regress_user1', 1), |
||||
('rls_regress_user2', 2), |
||||
('rls_regress_user3', 3); |
||||
|
||||
CREATE TABLE category ( |
||||
cid int primary key, |
||||
cname text |
||||
); |
||||
GRANT ALL ON category TO public; |
||||
INSERT INTO category VALUES |
||||
(11, 'novel'), |
||||
(22, 'science fiction'), |
||||
(33, 'technology'), |
||||
(44, 'manga'); |
||||
|
||||
CREATE TABLE document ( |
||||
did int primary key, |
||||
cid int references category(cid), |
||||
dlevel int not null, |
||||
dauthor name, |
||||
dtitle text |
||||
); |
||||
GRANT ALL ON document TO public; |
||||
INSERT INTO document VALUES |
||||
( 1, 11, 1, 'rls_regress_user1', 'my first novel'), |
||||
( 2, 11, 2, 'rls_regress_user1', 'my second novel'), |
||||
( 3, 22, 2, 'rls_regress_user1', 'my science fiction'), |
||||
( 4, 44, 1, 'rls_regress_user1', 'my first manga'), |
||||
( 5, 44, 2, 'rls_regress_user1', 'my second manga'), |
||||
( 6, 22, 1, 'rls_regress_user2', 'great science fiction'), |
||||
( 7, 33, 2, 'rls_regress_user2', 'great technology book'), |
||||
( 8, 44, 1, 'rls_regress_user2', 'great manga'); |
||||
|
||||
ALTER TABLE document ENABLE ROW LEVEL SECURITY; |
||||
|
||||
-- user's security level must be higher that or equal to document's |
||||
CREATE POLICY p1 ON document |
||||
USING (dlevel <= (SELECT seclv FROM uaccount WHERE pguser = current_user)); |
||||
|
||||
-- viewpoint from rls_regress_user1 |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SET row_security TO ON; |
||||
SELECT * FROM document WHERE f_leak(dtitle) ORDER BY did; |
||||
SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle) ORDER BY did; |
||||
|
||||
-- viewpoint from rls_regress_user2 |
||||
SET SESSION AUTHORIZATION rls_regress_user2; |
||||
SELECT * FROM document WHERE f_leak(dtitle) ORDER BY did; |
||||
SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle) ORDER BY did; |
||||
|
||||
EXPLAIN (COSTS OFF) SELECT * FROM document WHERE f_leak(dtitle); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle); |
||||
|
||||
-- only owner can change row-level security |
||||
ALTER POLICY p1 ON document USING (true); --fail |
||||
DROP POLICY p1 ON document; --fail |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
ALTER POLICY p1 ON document USING (dauthor = current_user); |
||||
|
||||
-- viewpoint from rls_regress_user1 again |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM document WHERE f_leak(dtitle) ORDER BY did; |
||||
SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle) ORDER by did; |
||||
|
||||
-- viewpoint from rls_regres_user2 again |
||||
SET SESSION AUTHORIZATION rls_regress_user2; |
||||
SELECT * FROM document WHERE f_leak(dtitle) ORDER BY did; |
||||
SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle) ORDER by did; |
||||
|
||||
EXPLAIN (COSTS OFF) SELECT * FROM document WHERE f_leak(dtitle); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle); |
||||
|
||||
-- interaction of FK/PK constraints |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
CREATE POLICY p2 ON category |
||||
USING (CASE WHEN current_user = 'rls_regress_user1' THEN cid IN (11, 33) |
||||
WHEN current_user = 'rls_regress_user2' THEN cid IN (22, 44) |
||||
ELSE false END); |
||||
|
||||
ALTER TABLE category ENABLE ROW LEVEL SECURITY; |
||||
|
||||
-- cannot delete PK referenced by invisible FK |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM document d FULL OUTER JOIN category c on d.cid = c.cid; |
||||
DELETE FROM category WHERE cid = 33; -- fails with FK violation |
||||
|
||||
-- cannot insert FK referencing invisible PK |
||||
SET SESSION AUTHORIZATION rls_regress_user2; |
||||
SELECT * FROM document d FULL OUTER JOIN category c on d.cid = c.cid; |
||||
INSERT INTO document VALUES (10, 33, 1, current_user, 'hoge'); |
||||
|
||||
-- UNIQUE or PRIMARY KEY constraint violation DOES reveal presence of row |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
INSERT INTO document VALUES (8, 44, 1, 'rls_regress_user1', 'my third manga'); -- Must fail with unique violation, revealing presence of did we can't see |
||||
SELECT * FROM document WHERE did = 8; -- and confirm we can't see it |
||||
|
||||
-- database superuser cannot bypass RLS policy when enabled |
||||
RESET SESSION AUTHORIZATION; |
||||
SET row_security TO ON; |
||||
SELECT * FROM document; |
||||
SELECT * FROM category; |
||||
|
||||
-- database superuser cannot bypass RLS policy when FORCE enabled. |
||||
RESET SESSION AUTHORIZATION; |
||||
SET row_security TO FORCE; |
||||
SELECT * FROM document; |
||||
SELECT * FROM category; |
||||
|
||||
-- database superuser can bypass RLS policy when disabled |
||||
RESET SESSION AUTHORIZATION; |
||||
SET row_security TO OFF; |
||||
SELECT * FROM document; |
||||
SELECT * FROM category; |
||||
|
||||
-- database non-superuser with bypass privilege can bypass RLS policy when disabled |
||||
SET SESSION AUTHORIZATION rls_regress_exempt_user; |
||||
SET row_security TO OFF; |
||||
SELECT * FROM document; |
||||
SELECT * FROM category; |
||||
|
||||
-- RLS policy applies to table owner when FORCE enabled. |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
SET row_security TO FORCE; |
||||
SELECT * FROM document; |
||||
SELECT * FROM category; |
||||
|
||||
-- RLS policy does not apply to table owner when RLS enabled. |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
SET row_security TO ON; |
||||
SELECT * FROM document; |
||||
SELECT * FROM category; |
||||
|
||||
-- RLS policy does not apply to table owner when RLS disabled. |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
SET row_security TO OFF; |
||||
SELECT * FROM document; |
||||
SELECT * FROM category; |
||||
|
||||
-- |
||||
-- Table inheritance and RLS policy |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
|
||||
SET row_security TO ON; |
||||
|
||||
CREATE TABLE t1 (a int, junk1 text, b text) WITH OIDS; |
||||
ALTER TABLE t1 DROP COLUMN junk1; -- just a disturbing factor |
||||
GRANT ALL ON t1 TO public; |
||||
|
||||
COPY t1 FROM stdin WITH (oids); |
||||
101 1 aaa |
||||
102 2 bbb |
||||
103 3 ccc |
||||
104 4 ddd |
||||
\. |
||||
|
||||
CREATE TABLE t2 (c float) INHERITS (t1); |
||||
COPY t2 FROM stdin WITH (oids); |
||||
201 1 abc 1.1 |
||||
202 2 bcd 2.2 |
||||
203 3 cde 3.3 |
||||
204 4 def 4.4 |
||||
\. |
||||
|
||||
CREATE TABLE t3 (c text, b text, a int) WITH OIDS; |
||||
ALTER TABLE t3 INHERIT t1; |
||||
COPY t3(a,b,c) FROM stdin WITH (oids); |
||||
301 1 xxx X |
||||
302 2 yyy Y |
||||
303 3 zzz Z |
||||
\. |
||||
|
||||
CREATE POLICY p1 ON t1 FOR ALL TO PUBLIC USING (a % 2 = 0); -- be even number |
||||
CREATE POLICY p2 ON t2 FOR ALL TO PUBLIC USING (a % 2 = 1); -- be odd number |
||||
|
||||
ALTER TABLE t1 ENABLE ROW LEVEL SECURITY; |
||||
ALTER TABLE t2 ENABLE ROW LEVEL SECURITY; |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
|
||||
SELECT * FROM t1; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1; |
||||
|
||||
SELECT * FROM t1 WHERE f_leak(b); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1 WHERE f_leak(b); |
||||
|
||||
-- reference to system column |
||||
SELECT oid, * FROM t1; |
||||
EXPLAIN (COSTS OFF) SELECT *, t1 FROM t1; |
||||
|
||||
-- reference to whole-row reference |
||||
SELECT *, t1 FROM t1; |
||||
EXPLAIN (COSTS OFF) SELECT *, t1 FROM t1; |
||||
|
||||
-- for share/update lock |
||||
SELECT * FROM t1 FOR SHARE; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1 FOR SHARE; |
||||
|
||||
SELECT * FROM t1 WHERE f_leak(b) FOR SHARE; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1 WHERE f_leak(b) FOR SHARE; |
||||
|
||||
-- superuser is allowed to bypass RLS checks |
||||
RESET SESSION AUTHORIZATION; |
||||
SET row_security TO OFF; |
||||
SELECT * FROM t1 WHERE f_leak(b); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1 WHERE f_leak(b); |
||||
|
||||
-- non-superuser with bypass privilege can bypass RLS policy when disabled |
||||
SET SESSION AUTHORIZATION rls_regress_exempt_user; |
||||
SET row_security TO OFF; |
||||
SELECT * FROM t1 WHERE f_leak(b); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1 WHERE f_leak(b); |
||||
|
||||
----- Dependencies ----- |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
SET row_security TO ON; |
||||
|
||||
CREATE TABLE dependee (x integer, y integer); |
||||
|
||||
CREATE TABLE dependent (x integer, y integer); |
||||
CREATE POLICY d1 ON dependent FOR ALL |
||||
TO PUBLIC |
||||
USING (x = (SELECT d.x FROM dependee d WHERE d.y = y)); |
||||
|
||||
DROP TABLE dependee; -- Should fail without CASCADE due to dependency on row-security qual? |
||||
|
||||
DROP TABLE dependee CASCADE; |
||||
|
||||
EXPLAIN (COSTS OFF) SELECT * FROM dependent; -- After drop, should be unqualified |
||||
|
||||
----- RECURSION ---- |
||||
|
||||
-- |
||||
-- Simple recursion |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
CREATE TABLE rec1 (x integer, y integer); |
||||
CREATE POLICY r1 ON rec1 USING (x = (SELECT r.x FROM rec1 r WHERE y = r.y)); |
||||
ALTER TABLE rec1 ENABLE ROW LEVEL SECURITY; |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM rec1; -- fail, direct recursion |
||||
|
||||
-- |
||||
-- Mutual recursion |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
CREATE TABLE rec2 (a integer, b integer); |
||||
ALTER POLICY r1 ON rec1 USING (x = (SELECT a FROM rec2 WHERE b = y)); |
||||
CREATE POLICY r2 ON rec2 USING (a = (SELECT x FROM rec1 WHERE y = b)); |
||||
ALTER TABLE rec2 ENABLE ROW LEVEL SECURITY; |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM rec1; -- fail, mutual recursion |
||||
|
||||
-- |
||||
-- Mutual recursion via views |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
CREATE VIEW rec1v AS SELECT * FROM rec1; |
||||
CREATE VIEW rec2v AS SELECT * FROM rec2; |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
ALTER POLICY r1 ON rec1 USING (x = (SELECT a FROM rec2v WHERE b = y)); |
||||
ALTER POLICY r2 ON rec2 USING (a = (SELECT x FROM rec1v WHERE y = b)); |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM rec1; -- fail, mutual recursion via views |
||||
|
||||
-- |
||||
-- Mutual recursion via .s.b views |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
DROP VIEW rec1v, rec2v CASCADE; |
||||
CREATE VIEW rec1v WITH (security_barrier) AS SELECT * FROM rec1; |
||||
CREATE VIEW rec2v WITH (security_barrier) AS SELECT * FROM rec2; |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
CREATE POLICY r1 ON rec1 USING (x = (SELECT a FROM rec2v WHERE b = y)); |
||||
CREATE POLICY r2 ON rec2 USING (a = (SELECT x FROM rec1v WHERE y = b)); |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM rec1; -- fail, mutual recursion via s.b. views |
||||
|
||||
-- |
||||
-- recursive RLS and VIEWs in policy |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
CREATE TABLE s1 (a int, b text); |
||||
INSERT INTO s1 (SELECT x, md5(x::text) FROM generate_series(-10,10) x); |
||||
|
||||
CREATE TABLE s2 (x int, y text); |
||||
INSERT INTO s2 (SELECT x, md5(x::text) FROM generate_series(-6,6) x); |
||||
|
||||
GRANT SELECT ON s1, s2 TO rls_regress_user1; |
||||
|
||||
CREATE POLICY p1 ON s1 USING (a in (select x from s2 where y like '%2f%')); |
||||
CREATE POLICY p2 ON s2 USING (x in (select a from s1 where b like '%22%')); |
||||
CREATE POLICY p3 ON s1 FOR INSERT WITH CHECK (a = (SELECT a FROM s1)); |
||||
|
||||
ALTER TABLE s1 ENABLE ROW LEVEL SECURITY; |
||||
ALTER TABLE s2 ENABLE ROW LEVEL SECURITY; |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
CREATE VIEW v2 AS SELECT * FROM s2 WHERE y like '%af%'; |
||||
SELECT * FROM s1 WHERE f_leak(b); -- fail (infinite recursion) |
||||
|
||||
INSERT INTO s1 VALUES (1, 'foo'); -- fail (infinite recursion) |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
DROP POLICY p3 on s1; |
||||
ALTER POLICY p2 ON s2 USING (x % 2 = 0); |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM s1 WHERE f_leak(b); -- OK |
||||
EXPLAIN (COSTS OFF) SELECT * FROM only s1 WHERE f_leak(b); |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
ALTER POLICY p1 ON s1 USING (a in (select x from v2)); -- using VIEW in RLS policy |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM s1 WHERE f_leak(b); -- OK |
||||
EXPLAIN (COSTS OFF) SELECT * FROM s1 WHERE f_leak(b); |
||||
|
||||
SELECT (SELECT x FROM s1 LIMIT 1) xx, * FROM s2 WHERE y like '%28%'; |
||||
EXPLAIN (COSTS OFF) SELECT (SELECT x FROM s1 LIMIT 1) xx, * FROM s2 WHERE y like '%28%'; |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
ALTER POLICY p2 ON s2 USING (x in (select a from s1 where b like '%d2%')); |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM s1 WHERE f_leak(b); -- fail (infinite recursion via view) |
||||
|
||||
-- prepared statement with rls_regress_user0 privilege |
||||
PREPARE p1(int) AS SELECT * FROM t1 WHERE a <= $1; |
||||
EXECUTE p1(2); |
||||
EXPLAIN (COSTS OFF) EXECUTE p1(2); |
||||
|
||||
-- superuser is allowed to bypass RLS checks |
||||
RESET SESSION AUTHORIZATION; |
||||
SET row_security TO OFF; |
||||
SELECT * FROM t1 WHERE f_leak(b); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1 WHERE f_leak(b); |
||||
|
||||
-- plan cache should be invalidated |
||||
EXECUTE p1(2); |
||||
EXPLAIN (COSTS OFF) EXECUTE p1(2); |
||||
|
||||
PREPARE p2(int) AS SELECT * FROM t1 WHERE a = $1; |
||||
EXECUTE p2(2); |
||||
EXPLAIN (COSTS OFF) EXECUTE p2(2); |
||||
|
||||
-- also, case when privilege switch from superuser |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SET row_security TO ON; |
||||
EXECUTE p2(2); |
||||
EXPLAIN (COSTS OFF) EXECUTE p2(2); |
||||
|
||||
-- |
||||
-- UPDATE / DELETE and Row-level security |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
EXPLAIN (COSTS OFF) UPDATE t1 SET b = b || b WHERE f_leak(b); |
||||
UPDATE t1 SET b = b || b WHERE f_leak(b); |
||||
|
||||
EXPLAIN (COSTS OFF) UPDATE only t1 SET b = b || '_updt' WHERE f_leak(b); |
||||
UPDATE only t1 SET b = b || '_updt' WHERE f_leak(b); |
||||
|
||||
-- returning clause with system column |
||||
UPDATE only t1 SET b = b WHERE f_leak(b) RETURNING oid, *, t1; |
||||
UPDATE t1 SET b = b WHERE f_leak(b) RETURNING *; |
||||
UPDATE t1 SET b = b WHERE f_leak(b) RETURNING oid, *, t1; |
||||
|
||||
RESET SESSION AUTHORIZATION; |
||||
SET row_security TO OFF; |
||||
SELECT * FROM t1; |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SET row_security TO ON; |
||||
EXPLAIN (COSTS OFF) DELETE FROM only t1 WHERE f_leak(b); |
||||
EXPLAIN (COSTS OFF) DELETE FROM t1 WHERE f_leak(b); |
||||
|
||||
DELETE FROM only t1 WHERE f_leak(b) RETURNING oid, *, t1; |
||||
DELETE FROM t1 WHERE f_leak(b) RETURNING oid, *, t1; |
||||
|
||||
-- |
||||
-- ROLE/GROUP |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
CREATE TABLE z1 (a int, b text); |
||||
|
||||
GRANT SELECT ON z1 TO rls_regress_group1, rls_regress_group2, |
||||
rls_regress_user1, rls_regress_user2; |
||||
|
||||
INSERT INTO z1 VALUES |
||||
(1, 'aaa'), |
||||
(2, 'bbb'), |
||||
(3, 'ccc'), |
||||
(4, 'ddd'); |
||||
|
||||
CREATE POLICY p1 ON z1 TO rls_regress_group1 USING (a % 2 = 0); |
||||
CREATE POLICY p2 ON z1 TO rls_regress_group2 USING (a % 2 = 1); |
||||
|
||||
ALTER TABLE z1 ENABLE ROW LEVEL SECURITY; |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM z1 WHERE f_leak(b); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM z1 WHERE f_leak(b); |
||||
|
||||
SET ROLE rls_regress_group1; |
||||
SELECT * FROM z1 WHERE f_leak(b); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM z1 WHERE f_leak(b); |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user2; |
||||
SELECT * FROM z1 WHERE f_leak(b); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM z1 WHERE f_leak(b); |
||||
|
||||
SET ROLE rls_regress_group2; |
||||
SELECT * FROM z1 WHERE f_leak(b); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM z1 WHERE f_leak(b); |
||||
|
||||
-- |
||||
-- Views should follow policy for view owner. |
||||
-- |
||||
-- View and Table owner are the same. |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
CREATE VIEW rls_view AS SELECT * FROM z1 WHERE f_leak(b); |
||||
GRANT SELECT ON rls_view TO rls_regress_user1; |
||||
|
||||
-- Query as role that is not owner of view or table. Should return all records. |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM rls_view; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM rls_view; |
||||
|
||||
-- Query as view/table owner. Should return all records. |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
SELECT * FROM rls_view; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM rls_view; |
||||
DROP VIEW rls_view; |
||||
|
||||
-- View and Table owners are different. |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
CREATE VIEW rls_view AS SELECT * FROM z1 WHERE f_leak(b); |
||||
GRANT SELECT ON rls_view TO rls_regress_user0; |
||||
|
||||
-- Query as role that is not owner of view but is owner of table. |
||||
-- Should return records based on view owner policies. |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
SELECT * FROM rls_view; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM rls_view; |
||||
|
||||
-- Query as role that is not owner of table but is owner of view. |
||||
-- Should return records based on view owner policies. |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM rls_view; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM rls_view; |
||||
|
||||
-- Query as role that is not the owner of the table or view without permissions. |
||||
SET SESSION AUTHORIZATION rls_regress_user2; |
||||
SELECT * FROM rls_view; --fail - permission denied. |
||||
EXPLAIN (COSTS OFF) SELECT * FROM rls_view; --fail - permission denied. |
||||
|
||||
-- Query as role that is not the owner of the table or view with permissions. |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
GRANT SELECT ON rls_view TO rls_regress_user2; |
||||
SELECT * FROM rls_view; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM rls_view; |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
DROP VIEW rls_view; |
||||
|
||||
-- |
||||
-- Command specific |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
|
||||
CREATE TABLE x1 (a int, b text, c text); |
||||
GRANT ALL ON x1 TO PUBLIC; |
||||
|
||||
INSERT INTO x1 VALUES |
||||
(1, 'abc', 'rls_regress_user1'), |
||||
(2, 'bcd', 'rls_regress_user1'), |
||||
(3, 'cde', 'rls_regress_user2'), |
||||
(4, 'def', 'rls_regress_user2'), |
||||
(5, 'efg', 'rls_regress_user1'), |
||||
(6, 'fgh', 'rls_regress_user1'), |
||||
(7, 'fgh', 'rls_regress_user2'), |
||||
(8, 'fgh', 'rls_regress_user2'); |
||||
|
||||
CREATE POLICY p0 ON x1 FOR ALL USING (c = current_user); |
||||
CREATE POLICY p1 ON x1 FOR SELECT USING (a % 2 = 0); |
||||
CREATE POLICY p2 ON x1 FOR INSERT WITH CHECK (a % 2 = 1); |
||||
CREATE POLICY p3 ON x1 FOR UPDATE USING (a % 2 = 0); |
||||
CREATE POLICY p4 ON x1 FOR DELETE USING (a < 8); |
||||
|
||||
ALTER TABLE x1 ENABLE ROW LEVEL SECURITY; |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM x1 WHERE f_leak(b) ORDER BY a ASC; |
||||
UPDATE x1 SET b = b || '_updt' WHERE f_leak(b) RETURNING *; |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user2; |
||||
SELECT * FROM x1 WHERE f_leak(b) ORDER BY a ASC; |
||||
UPDATE x1 SET b = b || '_updt' WHERE f_leak(b) RETURNING *; |
||||
DELETE FROM x1 WHERE f_leak(b) RETURNING *; |
||||
|
||||
-- |
||||
-- Duplicate Policy Names |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
CREATE TABLE y1 (a int, b text); |
||||
CREATE TABLE y2 (a int, b text); |
||||
|
||||
GRANT ALL ON y1, y2 TO rls_regress_user1; |
||||
|
||||
CREATE POLICY p1 ON y1 FOR ALL USING (a % 2 = 0); |
||||
CREATE POLICY p2 ON y1 FOR SELECT USING (a > 2); |
||||
CREATE POLICY p1 ON y1 FOR SELECT USING (a % 2 = 1); --fail |
||||
CREATE POLICY p1 ON y2 FOR ALL USING (a % 2 = 0); --OK |
||||
|
||||
ALTER TABLE y1 ENABLE ROW LEVEL SECURITY; |
||||
ALTER TABLE y2 ENABLE ROW LEVEL SECURITY; |
||||
|
||||
-- |
||||
-- Expression structure with SBV |
||||
-- |
||||
-- Create view as table owner. RLS should NOT be applied. |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
CREATE VIEW rls_sbv WITH (security_barrier) AS |
||||
SELECT * FROM y1 WHERE f_leak(b); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM rls_sbv WHERE (a = 1); |
||||
DROP VIEW rls_sbv; |
||||
|
||||
-- Create view as role that does not own table. RLS should be applied. |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
CREATE VIEW rls_sbv WITH (security_barrier) AS |
||||
SELECT * FROM y1 WHERE f_leak(b); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM rls_sbv WHERE (a = 1); |
||||
DROP VIEW rls_sbv; |
||||
|
||||
-- |
||||
-- Expression structure |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
INSERT INTO y2 (SELECT x, md5(x::text) FROM generate_series(0,20) x); |
||||
CREATE POLICY p2 ON y2 USING (a % 3 = 0); |
||||
CREATE POLICY p3 ON y2 USING (a % 4 = 0); |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM y2 WHERE f_leak(b); |
||||
EXPLAIN (COSTS OFF) SELECT * FROM y2 WHERE f_leak(b); |
||||
|
||||
-- |
||||
-- Plancache invalidate on user change. |
||||
-- |
||||
RESET SESSION AUTHORIZATION; |
||||
DROP TABLE t1 CASCADE; |
||||
CREATE TABLE t1 (a integer); |
||||
|
||||
GRANT SELECT ON t1 TO rls_regress_user1, rls_regress_user2; |
||||
|
||||
CREATE POLICY p1 ON t1 TO rls_regress_user1 USING ((a % 2) = 0); |
||||
CREATE POLICY p2 ON t1 TO rls_regress_user2 USING ((a % 4) = 0); |
||||
|
||||
ALTER TABLE t1 ENABLE ROW LEVEL SECURITY; |
||||
|
||||
SET ROLE rls_regress_user1; |
||||
PREPARE role_inval AS SELECT * FROM t1; |
||||
EXPLAIN (COSTS OFF) EXECUTE role_inval; |
||||
|
||||
SET ROLE rls_regress_user2; |
||||
EXPLAIN (COSTS OFF) EXECUTE role_inval; |
||||
|
||||
-- |
||||
-- CTE and RLS |
||||
-- |
||||
RESET SESSION AUTHORIZATION; |
||||
DROP TABLE t1 CASCADE; |
||||
CREATE TABLE t1 (a integer, b text); |
||||
CREATE POLICY p1 ON t1 USING (a % 2 = 0); |
||||
|
||||
ALTER TABLE t1 ENABLE ROW LEVEL SECURITY; |
||||
|
||||
GRANT ALL ON t1 TO rls_regress_user1; |
||||
|
||||
INSERT INTO t1 (SELECT x, md5(x::text) FROM generate_series(0,20) x); |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
|
||||
WITH cte1 AS (SELECT * FROM t1 WHERE f_leak(b)) SELECT * FROM cte1; |
||||
EXPLAIN (COSTS OFF) WITH cte1 AS (SELECT * FROM t1 WHERE f_leak(b)) SELECT * FROM cte1; |
||||
|
||||
WITH cte1 AS (UPDATE t1 SET a = a + 1 RETURNING *) SELECT * FROM cte1; --fail |
||||
WITH cte1 AS (UPDATE t1 SET a = a RETURNING *) SELECT * FROM cte1; --ok |
||||
|
||||
WITH cte1 AS (INSERT INTO t1 VALUES (21, 'Fail') RETURNING *) SELECT * FROM cte1; --fail |
||||
WITH cte1 AS (INSERT INTO t1 VALUES (20, 'Success') RETURNING *) SELECT * FROM cte1; --ok |
||||
|
||||
-- |
||||
-- Rename Policy |
||||
-- |
||||
RESET SESSION AUTHORIZATION; |
||||
ALTER POLICY p1 ON t1 RENAME TO p1; --fail |
||||
|
||||
SELECT rsecpolname, relname |
||||
FROM pg_rowsecurity rs |
||||
JOIN pg_class pc ON (pc.oid = rs.rsecrelid) |
||||
WHERE relname = 't1'; |
||||
|
||||
ALTER POLICY p1 ON t1 RENAME TO p2; --ok |
||||
|
||||
SELECT rsecpolname, relname |
||||
FROM pg_rowsecurity rs |
||||
JOIN pg_class pc ON (pc.oid = rs.rsecrelid) |
||||
WHERE relname = 't1'; |
||||
|
||||
-- |
||||
-- Check INSERT SELECT |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
CREATE TABLE t2 (a integer, b text); |
||||
INSERT INTO t2 (SELECT * FROM t1); |
||||
EXPLAIN (COSTS OFF) INSERT INTO t2 (SELECT * FROM t1); |
||||
SELECT * FROM t2; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t2; |
||||
CREATE TABLE t3 AS SELECT * FROM t1; |
||||
SELECT * FROM t3; |
||||
SELECT * INTO t4 FROM t1; |
||||
SELECT * FROM t4; |
||||
|
||||
-- |
||||
-- RLS with JOIN |
||||
-- |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
CREATE TABLE blog (id integer, author text, post text); |
||||
CREATE TABLE comment (blog_id integer, message text); |
||||
|
||||
GRANT ALL ON blog, comment TO rls_regress_user1; |
||||
|
||||
CREATE POLICY blog_1 ON blog USING (id % 2 = 0); |
||||
|
||||
ALTER TABLE blog ENABLE ROW LEVEL SECURITY; |
||||
|
||||
INSERT INTO blog VALUES |
||||
(1, 'alice', 'blog #1'), |
||||
(2, 'bob', 'blog #1'), |
||||
(3, 'alice', 'blog #2'), |
||||
(4, 'alice', 'blog #3'), |
||||
(5, 'john', 'blog #1'); |
||||
|
||||
INSERT INTO comment VALUES |
||||
(1, 'cool blog'), |
||||
(1, 'fun blog'), |
||||
(3, 'crazy blog'), |
||||
(5, 'what?'), |
||||
(4, 'insane!'), |
||||
(2, 'who did it?'); |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
-- Check RLS JOIN with Non-RLS. |
||||
SELECT id, author, message FROM blog JOIN comment ON id = blog_id; |
||||
-- Check Non-RLS JOIN with RLS. |
||||
SELECT id, author, message FROM comment JOIN blog ON id = blog_id; |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
CREATE POLICY comment_1 ON comment USING (blog_id < 4); |
||||
|
||||
ALTER TABLE comment ENABLE ROW LEVEL SECURITY; |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
-- Check RLS JOIN RLS |
||||
SELECT id, author, message FROM blog JOIN comment ON id = blog_id; |
||||
SELECT id, author, message FROM comment JOIN blog ON id = blog_id; |
||||
|
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
DROP TABLE blog, comment; |
||||
|
||||
-- |
||||
-- Default Deny Policy |
||||
-- |
||||
RESET SESSION AUTHORIZATION; |
||||
DROP POLICY p2 ON t1; |
||||
ALTER TABLE t1 OWNER TO rls_regress_user0; |
||||
|
||||
-- Check that default deny does not apply to superuser. |
||||
RESET SESSION AUTHORIZATION; |
||||
SELECT * FROM t1; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1; |
||||
|
||||
-- Check that default deny does not apply to table owner. |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
SELECT * FROM t1; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1; |
||||
|
||||
-- Check that default deny does apply to superuser when RLS force. |
||||
SET row_security TO FORCE; |
||||
RESET SESSION AUTHORIZATION; |
||||
SELECT * FROM t1; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1; |
||||
|
||||
-- Check that default deny does apply to table owner when RLS force. |
||||
SET SESSION AUTHORIZATION rls_regress_user0; |
||||
SELECT * FROM t1; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1; |
||||
|
||||
-- Check that default deny applies to non-owner/non-superuser when RLS on. |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SET row_security TO ON; |
||||
SELECT * FROM t1; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1; |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SELECT * FROM t1; |
||||
EXPLAIN (COSTS OFF) SELECT * FROM t1; |
||||
|
||||
-- |
||||
-- Event Triggers |
||||
-- |
||||
RESET SESSION AUTHORIZATION; |
||||
CREATE TABLE event_trigger_test (a integer, b text); |
||||
|
||||
CREATE OR REPLACE FUNCTION start_command() |
||||
RETURNS event_trigger AS $$ |
||||
BEGIN |
||||
RAISE NOTICE '% - ddl_command_start', tg_tag; |
||||
END; |
||||
$$ LANGUAGE plpgsql; |
||||
|
||||
CREATE OR REPLACE FUNCTION end_command() |
||||
RETURNS event_trigger AS $$ |
||||
BEGIN |
||||
RAISE NOTICE '% - ddl_command_end', tg_tag; |
||||
END; |
||||
$$ LANGUAGE plpgsql; |
||||
|
||||
CREATE OR REPLACE FUNCTION drop_sql_command() |
||||
RETURNS event_trigger AS $$ |
||||
BEGIN |
||||
RAISE NOTICE '% - sql_drop', tg_tag; |
||||
END; |
||||
$$ LANGUAGE plpgsql; |
||||
|
||||
CREATE EVENT TRIGGER start_rls_command ON ddl_command_start |
||||
WHEN TAG IN ('CREATE POLICY', 'ALTER POLICY', 'DROP POLICY') EXECUTE PROCEDURE start_command(); |
||||
|
||||
CREATE EVENT TRIGGER end_rls_command ON ddl_command_end |
||||
WHEN TAG IN ('CREATE POLICY', 'ALTER POLICY', 'DROP POLICY') EXECUTE PROCEDURE end_command(); |
||||
|
||||
CREATE EVENT TRIGGER sql_drop_command ON sql_drop |
||||
WHEN TAG IN ('DROP POLICY') EXECUTE PROCEDURE drop_sql_command(); |
||||
|
||||
CREATE POLICY p1 ON event_trigger_test USING (FALSE); |
||||
ALTER POLICY p1 ON event_trigger_test USING (TRUE); |
||||
ALTER POLICY p1 ON event_trigger_test RENAME TO p2; |
||||
DROP POLICY p2 ON event_trigger_test; |
||||
|
||||
DROP EVENT TRIGGER start_rls_command; |
||||
DROP EVENT TRIGGER end_rls_command; |
||||
DROP EVENT TRIGGER sql_drop_command; |
||||
|
||||
-- |
||||
-- COPY TO/FROM |
||||
-- |
||||
|
||||
RESET SESSION AUTHORIZATION; |
||||
DROP TABLE copy_t CASCADE; |
||||
CREATE TABLE copy_t (a integer, b text); |
||||
CREATE POLICY p1 ON copy_t USING (a % 2 = 0); |
||||
|
||||
ALTER TABLE copy_t ENABLE ROW LEVEL SECURITY; |
||||
|
||||
GRANT ALL ON copy_t TO rls_regress_user1, rls_regress_exempt_user; |
||||
|
||||
INSERT INTO copy_t (SELECT x, md5(x::text) FROM generate_series(0,10) x); |
||||
|
||||
-- Check COPY TO as Superuser/owner. |
||||
RESET SESSION AUTHORIZATION; |
||||
SET row_security TO OFF; |
||||
COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; |
||||
SET row_security TO ON; |
||||
COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; |
||||
SET row_security TO FORCE; |
||||
COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; |
||||
|
||||
-- Check COPY TO as user with permissions. |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SET row_security TO OFF; |
||||
COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --fail - insufficient to bypass rls |
||||
SET row_security TO ON; |
||||
COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --ok |
||||
SET row_security TO FORCE; |
||||
COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --ok |
||||
|
||||
-- Check COPY TO as user with permissions and BYPASSRLS |
||||
SET SESSION AUTHORIZATION rls_regress_exempt_user; |
||||
SET row_security TO OFF; |
||||
COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --ok |
||||
SET row_security TO ON; |
||||
COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --ok |
||||
SET row_security TO FORCE; |
||||
COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --ok |
||||
|
||||
-- Check COPY TO as user without permissions.SET row_security TO OFF; |
||||
SET SESSION AUTHORIZATION rls_regress_user2; |
||||
SET row_security TO OFF; |
||||
COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --fail - insufficient to bypass rls |
||||
SET row_security TO ON; |
||||
COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --fail - permission denied |
||||
SET row_security TO FORCE; |
||||
COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --fail - permission denied |
||||
|
||||
-- Check COPY FROM as Superuser/owner. |
||||
RESET SESSION AUTHORIZATION; |
||||
SET row_security TO OFF; |
||||
COPY copy_t FROM STDIN; --ok |
||||
1 abc |
||||
2 bcd |
||||
3 cde |
||||
4 def |
||||
\. |
||||
SET row_security TO ON; |
||||
COPY copy_t FROM STDIN; --ok |
||||
1 abc |
||||
2 bcd |
||||
3 cde |
||||
4 def |
||||
\. |
||||
SET row_security TO FORCE; |
||||
COPY copy_t FROM STDIN; --fail - COPY FROM not supported by RLS. |
||||
|
||||
-- Check COPY FROM as user with permissions. |
||||
SET SESSION AUTHORIZATION rls_regress_user1; |
||||
SET row_security TO OFF; |
||||
COPY copy_t FROM STDIN; --fail - insufficient privilege to bypass rls. |
||||
SET row_security TO ON; |
||||
COPY copy_t FROM STDIN; --fail - COPY FROM not supported by RLS. |
||||
SET row_security TO FORCE; |
||||
COPY copy_t FROM STDIN; --fail - COPY FROM not supported by RLS. |
||||
|
||||
-- Check COPY TO as user with permissions and BYPASSRLS |
||||
SET SESSION AUTHORIZATION rls_regress_exempt_user; |
||||
SET row_security TO OFF; |
||||
COPY copy_t FROM STDIN; --ok |
||||
1 abc |
||||
2 bcd |
||||
3 cde |
||||
4 def |
||||
\. |
||||
SET row_security TO ON; |
||||
COPY copy_t FROM STDIN; --fail - COPY FROM not supported by RLS. |
||||
SET row_security TO FORCE; |
||||
COPY copy_t FROM STDIN; --fail - COPY FROM not supported by RLS. |
||||
|
||||
-- Check COPY FROM as user without permissions. |
||||
SET SESSION AUTHORIZATION rls_regress_user2; |
||||
SET row_security TO OFF; |
||||
COPY copy_t FROM STDIN; --fail - permission denied. |
||||
SET row_security TO ON; |
||||
COPY copy_t FROM STDIN; --fail - permission denied. |
||||
SET row_security TO FORCE; |
||||
COPY copy_t FROM STDIN; --fail - permission denied. |
||||
|
||||
RESET SESSION AUTHORIZATION; |
||||
DROP TABLE copy_t; |
||||
|
||||
-- |
||||
-- Clean up objects |
||||
-- |
||||
RESET SESSION AUTHORIZATION; |
||||
|
||||
DROP SCHEMA rls_regress_schema CASCADE; |
||||
|
||||
DROP USER rls_regress_user0; |
||||
DROP USER rls_regress_user1; |
||||
DROP USER rls_regress_user2; |
||||
Loading…
Reference in new issue