# Row-level security and policies

Every table in a project decides for itself which rows the application may read and change. The database enforces it on every request, whatever your application's code does. You set it up on the project's **Security → Access rules** page.

## The three things that decide what the application gets

1. **What the application may do to the table at all.** Read rows, add rows, change rows, delete rows. Set under "The application may" on the Access rules page. Nothing allowed means nothing happens, whatever else is set.
2. **Whether row-level security is on.** Off means the application gets *every* row it is allowed to touch, for every organization and person. On means it gets only the rows a policy lets through.
3. **The policies.** Each is a rule the database checks against every row. With row-level security on and no policy, the application gets no rows.

A request through the API always runs as the application's own database role, acting for the signed-in person. A secret key does not skip row-level security: it acts for the one organization named in `x-organization-id`, with no person signed in.

## Safe by default

A table you create in the table editor, the SQL workspace, a migration or through the connector starts **closed**: row-level security on and no policy. Open it when you are ready.

## Asking who is calling

A rule uses these functions.

| Function | Gives | Meaning |
|---|---|---|
| `core.app_user()` | uuid | The signed-in user making the request. Null when nobody is signed in (a secret key acting for an organization). |
| `core.app_org()` | uuid | The organization the request acts for. |
| `core.current_app()` | text | The application the database connection belongs to. |

## How a policy reads

- **For**: which actions it covers. Everything, or only reading, adding, changing or deleting.
- **Using**: which *existing* rows are visible to that action.
- **With check**: what a *new or changed* row must satisfy. Leave it out and a person could write a row into someone else's organization.

Several policies on one table add up: a row is let through if any one of them lets it through.

## Policies people actually use

### Only rows of the caller's organization

The usual one for a table with an `organization_id` column.

```
for everything
using       organization_id = core.app_org()
with check  organization_id = core.app_org()
```

In SQL:

```sql
create policy own_organization on notes
  for all
  using (organization_id = core.app_org())
  with check (organization_id = core.app_org());
```

### Only rows the caller owns

```sql
create policy own_rows on drafts
  for all
  using (owner_id = core.app_user())
  with check (owner_id = core.app_user());
```

### Everyone in the organization reads, only the owner writes

Two policies. The first covers reading; the second covers everything for the owner.

```sql
create policy read_organization on documents
  for select
  using (organization_id = core.app_org());

create policy own_rows on documents
  for all
  using (owner_id = core.app_user())
  with check (owner_id = core.app_user() and organization_id = core.app_org());
```

### Roles inside an organization

There is no built-in list of roles inside an organization. Keep roles in a table of your own and look them up in the rule:

```sql
create policy managers_delete on invoices
  for delete
  using (
    organization_id = core.app_org()
    and exists (select 1 from memberships m where m.user_id = core.app_user() and m.role = 'manager')
  );
```

If the lookup table is itself protected, wrap the lookup in a function marked `security definer` with a fixed `search_path`, and allow the application's role to execute it:

```sql
create function is_manager() returns boolean
  language sql stable security definer set search_path = p_abcdefghijklmnopqrst, pg_temp as $$
  select exists (select 1 from memberships m
                 where m.user_id = core.app_user() and m.organization_id = core.app_org() and m.role = 'manager')
$$;
```

The fixed search path names your project's own schema, which is `p_` followed by the project ID for a project made in the console (`rezin projects --json` shows it).

### Rows anyone signed in may read

```sql
create policy read_all_signed_in on announcements
  for select
  using (core.app_user() is not null);
```

A rule that is simply `true` lets every caller of the project read every row, across organizations. The advisor flags it. Use it only for data that is the same for everyone.

## On the Access rules page

Security, then Access rules. Every table of the project is a card, and a box at the top finds a table or a rule by name.

Each card shows:

- whether row-level security is **on** or **off**, and a line in plain words when the table needs attention: off, closed (on with no rule), or rules with nothing allowed;
- what the application may do to the table at all: read, add, change, delete rows. A rule narrows this; it allows nothing by itself;
- every rule: its name, what it applies to (reading, adding, changing, deleting or everything), which rows, and what new or changed rows must satisfy.

Row-level security is switched on automatically for every table you create, so a new table starts closed.

### Adding or changing a rule

**New rule** on a table's card opens the editor, which has three ways to arrive at the same thing:

- **Templates**: same organization, owner only, signed-in read, public read, and by role (people listed with a role in another of your tables). Pick the columns and press Use.
- **Builder**: conditions on the table's own columns ("is the signed-in account", "is the caller's organization", "equals", "is filled in" and so on), joined by all or any.
- **Expression**: the rule itself, as written in this page's examples.

Whichever you use, you end on the expression and can read it before saving.

**Check** asks the database to make the rule and then undoes it. You see the rule exactly as the database reads it, or the database's own error, and a warning when the rule is simply `true`. Saving runs the same check first, so a rule that does not parse is never stored.

A rule is one expression; the console refuses anything that tries to be more. Each change is stored one statement at a time and is on the audit record.

### Turning row-level security off

Possible, and almost never what you want: the rules stop applying and the application reaches every row it is allowed to touch. The console asks you to type the table's name first.

### Tables made by your migrations

A table your own migrations created is marked **Made by migrations**. Its rules are shown in full. Because the rules of such a table normally live in your migrations, changing one here asks you to type the table's name first: the change takes effect at once, but your migrations will not know about it.

## Check it: "View as"

**View as…** on a table's card. Pick one of the project's accounts. The console fetches the rows the way the application would, as the application's role with that person signed in, and shows how many of the table's rows they are given and the first fifty. Nothing is changed, and the check is recorded.

It needs at least one active account in the project.

## The advisor

On the project's Home and Access rules pages. It lists:

- a table with row-level security **off** that the application can touch (fix: turn it on, then add a policy);
- a policy whose rule is simply `true`;
- a policy written for every database role instead of the application's own;
- a table with policies that the application is not allowed to touch at all;
- the application holding rights it does not need, such as emptying a table or adding triggers, with a button that removes them;
- a function that runs with its owner's rights and has no fixed search path.

A table with row-level security on and no policy is listed as a note, not a fault: it is closed, which is safe.

## Row-level security elsewhere

- **Realtime** reads each changed row again as the listener; only a row their policies let through is sent. See [Realtime](https://rezincore.com/docs/realtime.md).
- **The SQL workspace, the table editor and the tools** run as the project's own role and see every row. They are for the project's members.
- **Webhooks** are set up by an owner and send what the owner chose; they do not act for a user.
