# Row-level security and access
Source: https://sovaria.in/docs/row-level-security

Decide who may use each table and which rows each app user sees — with access policies, Postgres row-level security and the auth helpers.

Secure by default: app users and the anon key can't touch a table until you allow it. You decide in two layers, and you can use either or both.

(Diagram: How Sovaria decides a table request — An access policy can deny outright. When one allows — or none decides and the table has RLS enabled and forced — Postgres row-level security picks the rows; with no decision and no forced RLS the request is refused.)

| Layer | Decides | Where you set it |
|---|---|---|
| **Access policies** | Whether this caller may run SELECT / INSERT / UPDATE / DELETE on the table at all. | **Policies** page, Row access presets, `sov policy`, `sovaria.policy` |
| **Postgres row-level security** | Which rows that caller sees and may change. | `create policy` in SQL, or the **Owner only** preset |

How a request is decided: if an access policy **denies** it, it's denied. If one **allows** it, Postgres RLS (when enabled) still filters the rows. If **no access policy decides**, the table is allowed only when it has RLS **enabled and forced** — then your Postgres policies decide alone (the familiar Supabase model). Otherwise the request fails with `403 … NO_POLICY_DEFINED`.

## Option A — Postgres policies only

Enable **and force** RLS, then write policies with the auth helpers. This is all you need for most apps.

SQL:
```sql
alter table orders enable row level security;
alter table orders force row level security;   -- required: lets Postgres policies decide

create policy "owner reads" on orders
  for select using (user_id = auth.uid());

create policy "owner creates" on orders
  for insert with check (user_id = auth.uid());
```

> **Note:** Why `force` matters when no access policy decides: Sovaria hands the decision to your Postgres policies alone only for tables where RLS is enabled **and forced**; otherwise it refuses the request instead of risking unfiltered rows.

**Which database role runs your app's queries.** Today app traffic runs as your project's database role, which owns its tables — and Postgres skips row-level security for a table's owner unless RLS is **forced**. That is why every recipe here enables *and* forces it. For the console and the service role key, Sovaria sets `app.rls_bypass` to `on` (and `auth.role()` is `service_role`); the **Owner only** preset includes `current_setting('app.rls_bypass', true) = 'on'` so your team and server code keep seeing every row. Add the same check to policies you write yourself, or the Table Editor will show your team only what an app user would see.

> **Rolling out:** A separate **app role** that owns nothing is being rolled out: app users, the anon key and custom API keys will run as `<project role>_app`, so row-level security filters them on every table where it is enabled (forced or not), platform tables such as `auth.users` can't be read and app traffic can never change the schema. It can draw ids from sequences (`nextval`, serial columns) but not change them: `setval()` is the team's, so one app user can't stop everyone else's inserts. Forcing RLS keeps working unchanged when it arrives.

## Option B — access policies (presets)

In **Policies** (or when creating a table) turn on a preset such as **Signed-in read** or **Owner only**. They are short rules in Sovaria's policy language, which you can also write yourself:

Policy:
```bash
# Signed-in users may read and write the "notes" table
ALLOW IF ctx.resource.name == "notes" AND ctx.action IN ["SELECT", "INSERT", "UPDATE", "DELETE"] AND ctx.actor.is_anonymous != True

# Nobody who is signed out may touch it
DENY IF ctx.resource.name == "notes" AND ctx.actor.is_anonymous == True
```

CLI:
```bash
sov policy templates
sov policy upsert pol_notes_signed_in --org <project-id> --name "[table:notes] Signed-in CRUD" \
  --spl 'ALLOW IF ctx.resource.name == "notes" AND ctx.actor.is_anonymous != True'
sov policy check --action sql:select --resource notes
```

## Auth helpers in SQL

Full details, including what each returns for every kind of caller: [Auth helpers in SQL](https://sovaria.in/docs/auth-helpers).

| Function | Returns |
|---|---|
| `auth.uid()` | The signed-in app user's id (`uuid`); `null` for anonymous requests (anon key only). |
| `auth.role()` | `authenticated` for signed-in users; `anon` for the anon key and custom API keys; `service_role` for the service key and the console. |
| `auth.email()` | The signed-in user's email, as typed at sign-up. |
| `auth.verified_email()` | The email once the user has confirmed it, else `null`. Use it in policies that give rows by address. |
| `auth.has_role('STAFF')` | `true` if the user has that app role (assigned under **Users**). |
| `auth.jwt()` | All claims of the access token as `jsonb`. |

## Common patterns

### Each user sees and changes only their own rows

SQL:
```sql
create policy "own rows" on notes
  for all using (owner_id = auth.uid()) with check (owner_id = auth.uid());
```

### Anyone can read, only staff can write

SQL:
```sql
create policy "public catalogue" on products
  for select using (true);

create policy "staff manage catalogue" on products
  for all using (auth.has_role('STAFF')) with check (auth.has_role('STAFF'));
```

### Team members see their team's rows

SQL:
```sql
create policy "team members" on documents
  for select using (
    team_id in (select team_id from team_members where user_id = auth.uid())
  );
```

## Calling your functions

A statement that reads no table but calls one of your functions — `select join_room($1)`, or `rpc('join_room')` over REST — is decided per function, as the resource `fn:<name>`. Nothing allows that by default: app users call a function once an access policy allows it. The function's own SQL still runs under row-level security (or as its owner when it is `security definer`). The same holds when the call sits inside a query on a table (`select grant_points() from books`, `where in_room(id)`): reading the table doesn't allow the function, so it needs its own `fn:<name>` rule too. Postgres's built-ins (`count`, `lower`…) and extensions' functions need no rule, and functions your row-level security policies call aren't checked separately.

Access policy:
```bash
ALLOW IF ctx.resource.name == "fn:join_room" AND ctx.actor.is_anonymous == False
```

App:
```ts
await sov.data.sql('select join_room($1)', [roomId])   // refused until a rule allows fn:join_room
```

Rules test:
```bash
# sovaria.rules.test.yaml
cases:
  - name: signed-in users can join rooms
    as: user
    do: read
    on: fn:join_room
    expect: allow
  - name: visitors can't
    as: guest
    do: read
    on: fn:join_room
    expect: deny
```

Known scalar functions — `auth.uid()`, `now()`, `lower()` and the like — need no rule. Functions that read tables named in a text argument (`query_to_xml` …) are refused to app users whatever the rules say.

## USING and WITH CHECK

- `using (...)` filters which existing rows a query can see, update or delete.
- `with check (...)` validates new or changed rows. Without it a user could write a row they can't read back.

## Test before you ship

- **Users → (a user) → Test session** gives you a short-lived session as that user, so you can run queries exactly as they would.
- **Simulation** runs a request against your policies without touching data and shows which rule decided it.
- **Policies → Security advisor** flags tables without protection, public buckets and risky keys.

> **Tip:** Index the columns your policies use (`create index on notes (owner_id)`). Policies run for every row a query touches.
