

# Secure your data

Your website’s code contains the backend URL and the publishable key, so anyone who opens your site can call the Amplify backend data API with them. Neither value is a secret. You control what each request can read and change with grants and row-level security (RLS) policies in your PostgreSQL migrations.

A request with only the publishable key uses the `anon` role, and a signed-in user’s request uses `authenticated`. For more information about the roles, see [API keys and roles](backend-keys.md). PostgreSQL checks two things for each request:
+  **Grants** – which roles can try an operation, such as `select`, on a table.
+  **Policies** – which rows the operation can read or change.

By default, anyone can sign up with an email address and a password, so `authenticated` means anyone who has an account, not only users that you approve. A policy that checks only the role exposes its rows to anyone who signs up. To turn off sign-up, see [Email and password](backend-auth-password.md).

Write a table, its grants and its policies in the same migration. For more information about migrations, see [Tables and migrations](backend-data.md).

## Grant access to a table
<a name="backend-rls-grant"></a>

A new table has no grants to `anon` or `authenticated`, so data API requests to it fail with `permission denied`. In the table’s migration, grant each role only the operations that your policies cover:

```sql
grant select on public.notes to authenticated;                  -- add anon only if signed-out visitors read it
grant insert, update, delete on public.notes to authenticated;  -- add anon only for tables that signed-out visitors write to
```

Use `bigint generated always as identity` or `uuid default gen_random_uuid()` keys. An insert with a key that’s already taken fails, even when the caller can’t read the row that has it. If callers can set the key, they can use those failures to find out which rows exist. If your table uses another kind of key, grant only the columns that clients write: `grant insert (body), update (body) on public.notes to authenticated;`.

## Turn on row-level security
<a name="backend-rls-enable"></a>

RLS is on for every new table in `public`. Turn it on in the table’s migration anyway, so the migration doesn’t depend on that default:

```sql
alter table public.notes enable row level security;
```

 `anon` and `authenticated` can’t read or write any row of a table that has RLS on and no policies. A read returns `[]` without an error, an update or delete changes 0 rows, and an insert fails with `409` `WRITE_CONFLICT`. None of these responses says that a policy is missing.

**Warning**  
 **Warning:** To fix missing rows, write a policy. Never turn off RLS or write `using (true)` on users' data: either one exposes every row through the data API.

## Write policies
<a name="backend-rls-policies"></a>

 `auth.uid()` returns the signed-in user’s ID as `text`. The following migration creates the `notes` table with its grants and policies. Each user can read and write only their own notes:

```sql
create table public.notes (
  id         bigint generated always as identity primary key,
  owner_id   text not null default auth.uid(),  -- text, to match auth.uid()
  body       text not null
);
create index notes_owner_idx on public.notes (owner_id);
alter table public.notes enable row level security;

create policy "notes_select_own" on public.notes for select
  to authenticated using ((select auth.uid()) = owner_id);
create policy "notes_insert_own" on public.notes for insert
  to authenticated with check ((select auth.uid()) = owner_id);
create policy "notes_update_own" on public.notes for update
  to authenticated using ((select auth.uid()) = owner_id)
  with check ((select auth.uid()) = owner_id);
create policy "notes_delete_own" on public.notes for delete
  to authenticated using ((select auth.uid()) = owner_id);

grant select, insert, update, delete on public.notes to authenticated;
```

The example follows these rules:
+  **Write one policy for each operation and role, and give it an owner check.** If a policy has `to authenticated` and no owner check, every signed-in user can use that operation on every row.
+  **Write `(select auth.uid())` in a policy, and index the owner column.** PostgreSQL runs `auth.uid()` once per statement when you wrap it in `select`.
+  **Make owner columns `text not null default auth.uid()`.** A policy that compares a `uuid` column with `auth.uid()` fails with `operator does not exist: uuid = text`. Write plain `auth.uid()` in the default, because PostgreSQL doesn’t allow a subquery in a `DEFAULT`.
+  **Pair each `update` policy with a `select` policy, and give it both `using` and `with check`.** An update changes only the rows that the caller can read through a `select` policy. A user can move a row to another owner when the `update` policy has no `with check`.

A role that can read a row through a policy can read every column of that row that the role has a grant on.

Before you trust `auth.email()` in a policy, also check `(auth.jwt()->>'email_verified')::boolean`.

## Common policy patterns
<a name="backend-rls-patterns"></a>

### Public read, owner write
<a name="backend-rls-public-read"></a>

Anyone can read the public rows of `routines`, and owners can also read their private rows. Only owners can write:

```sql
create policy "read_public_or_own" on public.routines for select to anon, authenticated
  using (is_public or owner_id = (select auth.uid()));
-- insert, update and delete policies as in notes
grant select on public.routines to anon, authenticated;
grant insert, update, delete on public.routines to authenticated;
```

### Admins from a table
<a name="backend-rls-admins"></a>

Keep admins and other app roles in a table. You can’t add claims to a user’s token, and users can change their own `name`, so don’t use a token claim to identify an admin.

```sql
create table public.admins (user_id text primary key);
alter table public.admins enable row level security;
create policy "admins_see_self" on public.admins for select to authenticated
  using (user_id = (select auth.uid()));
grant select on public.admins to authenticated;

create policy "own_or_admin_select" on public.orders for select to authenticated using (
  owner_id = (select auth.uid())
  or exists (select 1 from public.admins a where a.user_id = (select auth.uid()))
);
```

To make a user an admin in an environment, insert their ID after they sign up there. A migration runs in every environment, so it can’t add a user who exists in only one. Run the following commands. Replace `rosie@example.com` with the user’s email.

```bash
id=$(aws amplifygen3 backend user get --env production --email rosie@example.com --query Id --output text)
aws amplifygen3 db query "insert into public.admins (user_id) values ('$id')" --env production
```

### Members who see each other
<a name="backend-rls-members"></a>

To let the members of a list see each other, read the caller’s memberships through a `security definer` function in another schema. A policy on `list_members` that queries `list_members` itself fails with `infinite recursion detected in policy`. The following migration creates the function and the policy:

```sql
create schema private;
create function private.my_list_ids() returns setof bigint
  language sql stable security definer set search_path = ''
  as $$ select list_id from public.list_members where user_id = (select auth.uid()) $$;
grant usage on schema private to authenticated;
grant execute on function private.my_list_ids() to authenticated;
create policy "members_see_members" on public.list_members for select to authenticated
  using (list_id in (select private.my_list_ids()));
```

### Public counts over private rows
<a name="backend-rls-public-counts"></a>

To show totals or taken slots, keep the table’s policies owner-only. Return only the columns that everyone may see, such as `slot_id`, from a `security definer` function in `public`. Your app calls it with `backend.rpc('taken_slots')`. For more information, see [Call database functions](backend-data-api-rpc.md).

```sql
create function public.taken_slots() returns table (slot_id bigint)
  language sql stable security definer set search_path = ''
  as $$ select slot_id from public.bookings $$;
grant execute on function public.taken_slots() to authenticated;  -- add anon only for signed-out visitors
```

## Create views with security\_invoker
<a name="backend-rls-views"></a>

Create every view with `security_invoker = true`, so that PostgreSQL checks the caller against the policies on the view’s tables:

```sql
create view public.order_summaries with (security_invoker = true) as
  select o.id, o.total, c.name from public.orders o join public.customers c on c.id = o.customer_id;
```

If you leave the option out, the view still gets `security_invoker`. A view with `security_invoker = false` runs as its owner and returns every row that its query selects.

A materialized view has no `security_invoker` option. When you create or refresh it, it fills its rows with its owner’s access, so don’t grant a materialized view over users' data to `anon` or `authenticated`.

## Use security definer functions safely
<a name="backend-rls-definer"></a>

A `security definer` function runs as its owner, and RLS doesn’t apply to it.

**Important**  
 **Important:** Never add `security definer` to get past `permission denied`. Fix the grant or the policy instead.

When you write a `security definer` function:
+ Put it in a schema of your own, such as `private`, unless your app calls it. The data API serves only the `public` schema.
+ Check `(select auth.uid())` in its body, and return only what that caller may see.
+ Give it `set search_path = ''`, and qualify every name with its schema.
+ Any role with `execute` can call a function in `public` at `/rest/rpc/<name>`. A new function has no `execute` grant to `anon` or `authenticated`, so grant only the role that needs it.

## Test your policies
<a name="backend-rls-test"></a>

The `aws amplifygen3 db` commands log in as `amplify_admin`. That role can read every row and can’t switch to another role, so a query from these commands doesn’t test your policies. Test each policy change through the data API: as the owner, as a second user, and signed out. To test policies on the local backend, see [Develop locally](backend-local.md).

In the following steps, you test the `notes` table in the `preview` environment. Run `aws amplifygen3 backend info --env preview`, and replace `<backend-url>` and `<publishable-key>` with the `AMPLIFY_BACKEND_URL` and `AMPLIFY_BACKEND_PUBLISHABLE_KEY` values that it lists.

1. Sign up users A and B, and get a token for each. A token lasts 15 minutes.

   ```bash
   API=<backend-url>; KEY=<publishable-key>
   curl -s -X POST "$API/auth/sign-up/email" -H "apikey: $KEY" -H 'content-type: application/json' \
     -d '{"email":"a@example.com","password":"correct horse battery","name":"A"}'
   curl -s -c jar-a -X POST "$API/auth/sign-in/email" -H "apikey: $KEY" -H 'content-type: application/json' \
     -d '{"email":"a@example.com","password":"correct horse battery"}'
   JWT_A=$(curl -s -b jar-a -H "apikey: $KEY" "$API/auth/token" | jq -r '.token')
   # Repeat for b@example.com, with jar-b and JWT_B
   ```

1. Insert a row as A, then read it as B and signed out:

   ```bash
   ID=$(curl -s -X POST "$API/rest/notes" -H "apikey: $KEY" -H "Authorization: Bearer $JWT_A" \
     -H 'content-type: application/json' -H 'Prefer: return=representation' -d '{"body":"hello"}' | jq -r '.[0].id')  # the new row's id
   curl -s "$API/rest/notes?id=eq.$ID" -H "apikey: $KEY" -H "Authorization: Bearer $JWT_B"  # []
   curl -s "$API/rest/notes" -H "apikey: $KEY"                                            # 401, code 42501
   ```

   The insert often returns an `id` other than 1, because identity values aren’t reused, so keep the `id` that it returns. An update by B changes 0 rows, and an insert by B with A’s `owner_id` fails with `409`.

1. Delete the test row as A with `id=eq.$ID`. Then delete each test user with `aws amplifygen3 backend user delete --env preview --email <email> --yes`.

**Warning**  
 **Warning:** Your tables hold real data. Delete each test row by its key, never with an unscoped `delete from` or `truncate`.

To write the test in TypeScript, use the client SDK with one client for each user. For more information, see the [client SDK README](https://github.com/aws-amplifygen3/amplifygen3/blob/main/packages/client-sdk/js/README.md) on GitHub.

## Audit your tables
<a name="backend-rls-audit"></a>

Run the following commands to check a deployed database for RLS mistakes:

```bash
aws amplifygen3 db lint --env preview --level error
aws amplifygen3 db lint --env preview --fail-on error   # fails a CI job on any error
```

The command checks the `public` schema unless you pass `--schema`, such as `--schema public,private`. It reports these findings as errors: a table that `anon` or `authenticated` can query with RLS off (`rls_disabled_in_public`), a table that has policies but has RLS off, and a view that those roles can query and that isn’t `security_invoker`. Warnings include a write policy whose check is `true`, and a function without `set search_path`. With `--fail-on error`, the command exits with a non-zero status (255) on any error-level finding, including findings that `--level` hides.

## Errors
<a name="backend-rls-errors"></a>


| What you see | Cause | Fix | 
| --- | --- | --- | 
|  `42501` `permission denied for table <table>`, with `401` signed out or `403` signed in | No grant for the caller’s role | Grant the operation in a migration | 
|  `[]` from a read, or an update or delete that changes 0 rows | The caller can’t read the rows through any policy, or `update` has no `select` policy | Add the policy | 
|  `409` `WRITE_CONFLICT` on an insert or update | The new row fails a policy’s `with check`, or no `insert` policy exists | Check the owner value and the policy | 
|  `operator does not exist: uuid = text`  | A `uuid` owner column compared with `auth.uid()`  | Make the column `text`  | 
|  `infinite recursion detected in policy` (`42P17`) | A policy reads its own table | Use a `security definer` function in another schema | 

For other errors, see [Data API errors](backend-data-api-errors.md).