Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions apps/docs/content/guides/realtime/authorization.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,17 @@ By creating RLS policies on the `realtime.messages` table you can control the ac

<Admonition type="caution">

Realtime locks down the `realtime` schema to protect it against unexpected changes to guarantee the healthy operation of the Realtime service and avoid conflicts that could be caused by future migrations. Creating a table or function in `realtime` is expected to fail with `permission denied for schema realtime`, whether you run the SQL yourself or through the dashboard. Managing RLS policies on `realtime.messages` is allowed.
Realtime locks down the `realtime` schema to protect it against unexpected changes to guarantee the healthy operation of the Realtime service and avoid conflicts that could be caused by future migrations. Creating a table or function in `realtime` is expected to fail with `permission denied for schema realtime`, whether you run the SQL yourself or through the dashboard. Managing RLS policies on `realtime.messages` is allowed: [`supautils`](https://github.com/supabase/supautils) lets the `postgres` role run policy statements on that table without owning it.

Row level security (RLS) is enabled by default on table `realtime.messages`, you don't need to execute `ALTER TABLE realtime.messages ENABLE ROW LEVEL SECURITY`.
Row Level Security is already enabled on `realtime.messages`, so don't add `ALTER TABLE realtime.messages ENABLE ROW LEVEL SECURITY` to a migration. Postgres checks table ownership before it checks whether the setting would change, so the statement fails with `42501 must be owner of table messages`. That aborts the transaction, and every statement after it is skipped, including any `create policy` statements that follow.

Remove the `ALTER TABLE` line and the rest of the migration passes. If a migration needs to check that RLS is on, read the catalog:

```sql
select relrowsecurity from pg_class where oid = 'realtime.messages'::regclass;
```

If you hit that error, see [must be owner of table messages](/docs/guides/troubleshooting/realtime-must-be-owner-of-table-messages).

</Admonition>

Expand Down Expand Up @@ -402,6 +410,8 @@ Realtime updates the access policy cache for a client based on your RLS policies
- A client connects to Realtime and subscribes to a Channel
- A new JWT is sent to Realtime from a client via the [`access_token` message](/docs/guides/realtime/protocol#access-token)

This means that if you revoke a user's access (for example, by removing a row an RLS policy uses to grant it) while they're still connected, they'll keep receiving messages until their JWT expires or a new one is sent.

If a new JWT is never received on the Channel, the client will be disconnected when the JWT expires.

Make sure to keep the JWT expiration window short.
6 changes: 4 additions & 2 deletions apps/docs/content/guides/realtime/broadcast.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ select
jsonb_build_object('hello', 'world'), -- JSONB Payload
'event', -- Event name
'topic', -- Topic
false -- Public / Private flag
false -- Private flag - true: Private (default), false: Public
);
```

Expand All @@ -530,7 +530,7 @@ select
'\x012345'::bytea, -- bytea payload
'event', -- Event name
'topic', -- Topic
true -- Private / Public flag (defaults to true)
true -- Private flag - true: Private (default), false: Public
);
```

Expand Down Expand Up @@ -1020,6 +1020,8 @@ Broadcast Changes allows you to trigger messages from your database. To achieve

It uses partitioned tables per day, which allows performant deletion of your previous messages by dropping the physical tables of this partitioned table. Tables older than 3 days are deleted.

A client connecting over WebSocket creates those daily partitions. `realtime.send` does not. With no partition for today, the insert fails and Postgres logs a `WarnSendingBroadcastMessage` warning, so connect a client before you broadcast from the database. See [Realtime: `WarnSendingBroadcastMessage`](/docs/guides/troubleshooting/realtime-warn-sending-broadcast-message) if you hit that warning.

Broadcasting from the database works like a client-side broadcast, using WebSockets to send JSON payloads. [Realtime Authorization](/docs/guides/realtime/authorization) is required and enabled by default to protect your data.

Broadcast Changes provides two functions to help you send messages:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
---
title = "Realtime: \"must be owner of table messages\" when setting up Authorization"
topics = [ "realtime" ]
keywords = [ "realtime.messages", "must be owner", "42501", "row level security", "policy", "authorization", "broadcast", "migration" ]

[[errors]]
code = "42501"
message = "must be owner of table messages"
---

A migration that adds an RLS policy to `realtime.messages` fails:

```
ERROR: 42501: must be owner of table messages
```

## Cause

`realtime.messages` is owned by an internal role, `supabase_realtime_admin`. The `postgres` role is not a member of it and is not a superuser.

Policies still work because of [`supautils`](https://github.com/supabase/supautils), the extension that gives the `postgres` role its elevated permissions on a Supabase project. It lets `postgres` run `create policy`, `alter policy`, and `drop policy` on a fixed list of tables it does not own, and `realtime.messages` is on that list. The list covers policy statements only, so `ALTER TABLE` is still refused.

The failing statement is usually not the `create policy`. It's an `ALTER TABLE` earlier in the same migration:

```sql
alter table realtime.messages enable row level security;
alter table realtime.messages add column ...;
alter table realtime.messages owner to postgres;
```

The first one is the common case. RLS is already enabled on `realtime.messages`, and Postgres checks ownership before it checks whether the setting would change, so the statement fails on every project.

A failed statement aborts the transaction, so Postgres skips everything after it, including the `create policy`. `supabase db push` runs each migration file in one transaction, so the file rolls back and nothing is written to `supabase_migrations.schema_migrations`.

## Fix

Remove the `ALTER TABLE` line. Keep the policy:

```sql
create policy "authenticated can read messages on room-1"
on "realtime"."messages"
for select
to authenticated
using (
(select realtime.topic()) = 'room-1'
);
```

Run it from the SQL editor or with `supabase db push`. Both connect as `postgres`.

To check that RLS is on, read the catalog instead of setting it:

```sql
select relrowsecurity from pg_class where oid = 'realtime.messages'::regclass;
```

## What doesn't work

Granting the owning role fails, and support can't grant it either:

```sql
grant supabase_realtime_admin to postgres;
-- ERROR: 42501: "supabase_realtime_admin" role memberships are reserved, only superusers can grant them
```

Restarting the project changes nothing.

Wrapping the `ALTER TABLE` in a function or a `do` block changes nothing either. The ownership check still runs, and a `security definer` function owned by `postgres` is still not the table owner.

## What postgres can do on realtime.messages

The `Yes` rows are what `supautils` delegates, plus the privileges granted to `postgres` directly.

| Statement | Allowed |
| ----------------------------------------------------- | ------- |
| `create policy`, `alter policy`, `drop policy` | Yes |
| `comment on policy` | Yes |
| `select`, `insert` | Yes |
| `grant select`, `grant insert` to your own roles | Yes |
| `alter table` in any form | No |
| `drop table` | No |
| Creating tables or functions in the `realtime` schema | No |

See [Realtime Authorization](/docs/guides/realtime/authorization) for writing the policies.
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,24 @@ Calling `realtime.send` or `realtime.send_binary`, the broadcast REST endpoint,

</Admonition>

## Check which partitions you have

```sql
select c.relname
from pg_inherits i
join pg_class c on c.oid = i.inhrelid
where i.inhparent = 'realtime.messages'::regclass
order by c.relname;
```

The names are dates, so the result tells you which case you are in:

- One covers today. The missing partition is not the cause, so go to [When it is a real problem](#when-it-is-a-real-problem).
- They all end on a past date. Your window lapsed. The newest name is three days after the last time partitions were created, because each creation covers yesterday through three days ahead.
- No rows. No client has ever connected, so no partition was ever created.

Zero rows does not mean the Realtime migrations are missing. Those would fail this query with `42P01 relation "realtime.messages" does not exist`. If you see `42P01`, open a support ticket.

## How to avoid it

- Connect a client before broadcasting from the database. A live WebSocket connection both creates the partitions and starts the consumer that receives the message.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { QueryClient } from '@tanstack/react-query'
import { screen, waitFor, within } from '@testing-library/react'
import { HttpResponse } from 'msw'
import { describe, expect, it } from 'vitest'

import { DatabaseInfrastructureSection } from './DatabaseInfrastructureSection'
import type { InfraMonitoringMultiResponse } from '@/data/analytics/infra-monitoring-query'
import { databaseKeys } from '@/data/database/keys'
import { projectKeys } from '@/data/projects/keys'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'

const values: Record<string, number> = {
avg_cpu_usage: 25,
ram_usage: 60,
disk_io_consumption: 40,
disk_fs_used_system: 10,
disk_fs_used_wal: 5,
pg_database_size: 35,
disk_fs_size: 100,
pg_stat_database_num_backends: 12,
}

function mockMetrics(failedAttribute?: string, includeErrors = true) {
const requests: string[][] = []
addAPIMock({
method: 'get',
path: '/platform/projects/:ref/infra-monitoring',
response: ({ request }) => {
const attributes = new URL(request.url).searchParams.get('attributes')!.split(',')
requests.push(attributes)
const succeeded = attributes.filter(
(attribute) => failedAttribute !== '*' && attribute !== failedAttribute
)
const failed = attributes.filter((attribute) => !succeeded.includes(attribute))
const series = Object.fromEntries(
succeeded.map((attribute) => [
attribute,
{
totalAverage: values[attribute],
total: values[attribute],
format: '%',
yAxisLimit: 100,
},
])
)
const pointValues = Object.fromEntries(
succeeded.map((attribute) => [attribute, String(values[attribute])])
)
return HttpResponse.json<InfraMonitoringMultiResponse>({
series,
data: succeeded.length
? [{ period_start: '2026-09-24T00:00:00Z', values: pointValues }]
: [],
...(includeErrors
? {
errors: Object.fromEntries(
failed.map((attribute) => [attribute, { message: 'Metric is not supported' }])
),
}
: {}),
})
},
})
return requests
}

function renderMetrics() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
})
queryClient.setQueryData(projectKeys.detail('default'), {
ref: 'default',
status: 'ACTIVE_HEALTHY',
connectionString: 'postgresql://localhost/postgres',
})
queryClient.setQueryData(databaseKeys.maxConnections('default'), { maxConnections: 100 })
customRender(
<DatabaseInfrastructureSection
interval="1day"
refreshKey={0}
dbErrorRate={0}
isLoading={false}
/>,
{ queryClient }
)
}

function card(label: string) {
return within(screen.getByRole('link', { name: new RegExp(label) }))
}

describe('DatabaseInfrastructureSection batched metrics', () => {
it.each([false, true])(
'renders all metrics from one request (errors field: %s)',
async (includeErrors) => {
const requests = mockMetrics(undefined, includeErrors)
renderMetrics()

expect(await card('CPU').findByText('25%')).toBeInTheDocument()
expect(await card('Memory').findByText('60%')).toBeInTheDocument()
expect(await card('Disk IO').findByText('40%')).toBeInTheDocument()
expect(await card('Disk Usage').findByText('50%')).toBeInTheDocument()
expect(await card('Peak Connections').findByText('12/100')).toBeInTheDocument()
expect(requests).toHaveLength(1)
expect(requests[0].sort()).toEqual(Object.keys(values).sort())
}
)

it.each([
['disk_io_consumption', 'Disk IO'],
['disk_fs_used_wal', 'Disk Usage'],
['pg_stat_database_num_backends', 'Peak Connections'],
])('isolates a failed %s result to %s', async (attribute, label) => {
const requests = mockMetrics(attribute)
renderMetrics()

expect(await card(label).findByText('Metric is not supported')).toBeInTheDocument()
expect(await card('CPU').findByText('25%')).toBeInTheDocument()
expect(await card('Memory').findByText('60%')).toBeInTheDocument()
expect(screen.getAllByText('Metric is not supported')).toHaveLength(1)
expect(card(label).queryByText('0%')).not.toBeInTheDocument()
expect(requests).toHaveLength(1)
})

it('shows every affected card error when all results fail', async () => {
const requests = mockMetrics('*')
renderMetrics()
await waitFor(() => expect(screen.getAllByText('Metric is not supported')).toHaveLength(5))
expect(requests).toHaveLength(1)
})

it('does not display missing series as zero', async () => {
mockMetrics('disk_io_consumption', false)
renderMetrics()
expect(await card('Disk IO').findByText('Error loading data')).toBeInTheDocument()
expect(await card('CPU').findByText('25%')).toBeInTheDocument()
})

it('shows request-wide failures on every infrastructure card', async () => {
addAPIMock({
method: 'get',
path: '/platform/projects/:ref/infra-monitoring',
response: () =>
HttpResponse.json<APIErrorBody>({ message: 'Project not found' }, { status: 404 }),
})
renderMetrics()
await waitFor(() => expect(screen.getAllByText('Project not found')).toHaveLength(5))
})
})
Loading
Loading