new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Supabase · Realtime · all subjects

realtime/authorization

22 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Increased RLS complexity impacts database performance and connection latency

Increased RLS complexity can impact database performance and connection time, leading to higher connection latency and decreased join rates.

Realtime authorization uses RLS policies on realtime.messages table

Realtime authorization is controlled by creating Row Level Security (RLS) policies on the realtime.messages table in your database's realtime schema. Each RLS policy can control which clients can broadcast to a Channel, receive broadcasts from a Channel, publish presence to a Channel, or receive presence messages about other clients.

Disable 'Allow public access' setting to enforce private channels

To enforce private channels in Realtime, you must disable the 'Allow public access' setting in Realtime Settings at /dashboard/project/_/realtime/settings.

RLS is enabled by default on realtime.messages table

Row level security (RLS) is enabled by default on the realtime.messages table. You do not need to execute ALTER TABLE realtime.messages ENABLE ROW LEVEL SECURITY.

realtime schema is locked to prevent unexpected changes

The realtime schema is locked down to protect it against unexpected changes and guarantee healthy operation of the Realtime service. Creating a table or function in the realtime schema will fail with 'permission denied for schema realtime'. However, managing RLS policies on realtime.messages is allowed.

Realtime authorization validation happens at connection time

Authorization validation occurs when a user connects to Realtime. When their WebSocket connection is established and a Channel topic is joined, their permissions are calculated based on RLS policies on realtime.messages, user information from their Auth JWT, request headers, and the Channel topic they are trying to connect to.

Realtime does not store messages in realtime.messages table

When Realtime generates a policy for a client, it performs a query on the realtime.messages table and then rolls it back. Realtime does not store any messages in the realtime.messages table.

Two steps to implement Realtime Authorization

Using Realtime Authorization involves two steps: (1) In your database, create RLS policies on the realtime.messages table, and (2) In your client, instantiate the Realtime Channel with the config option private: true.

realtime.topic() helper function returns the Channel topic

The realtime.topic() helper function can be used when writing RLS policies on realtime.messages. It returns the Channel topic the user is attempting to connect to.

Access JWT claims in RLS policies using current_setting

User claims can be accessed in RLS policies using the current_setting function. The claims are available as a JSON object in the request.jwt.claims setting. For example, to access the email claim: (current_setting('request.jwt.claims'))::json ->> 'email'

Example: Combined RLS policy for writing broadcast and presence on topic

```sql create policy "authenticated can send broadcast and presence on topic" on "realtime"."messages" for insert to authenticated with check ( exists ( select user_id from rooms_users where user_id = (select auth.uid()) and room_topic = (select realtime.topic()) and realtime.messages.extension in ('broadcast', 'presence') ) ); ``` This policy allows authenticated users who are linked to the requested topic to send both broadcast and presence messages.

Client access policies are cached during connection

Client access policies are cached for the duration of the connection. Your database is not queried for every Channel message.

RLS policy cache is updated when client connects or sends new JWT

Realtime updates the access policy cache for a client based on RLS policies in two situations: (1) When a client connects to Realtime and subscribes to a Channel, and (2) When a new JWT is sent to Realtime from a client via the access_token message. If a new JWT is never received on the Channel, the client will be disconnected when the JWT expires.

Keep JWT expiration window short for security

When using Realtime Authorization, make sure to keep the JWT expiration window short. This is important because if a new JWT is never received on the Channel, the client will be disconnected when the JWT expires.

Database connection pool size setting

The 'Database connection pool size' setting determines the number of connections used for Realtime Authorization RLS checking.

Broadcast authorization requirement

Realtime Authorization is required for receiving Broadcast messages. An example policy that allows authenticated users to listen to messages from topics is: create policy "Authenticated users can receive broadcasts" on "realtime"."messages" for select to authenticated using ( true );

(Write) Private Channel Subscription RLS Execution Time report

The (Write) Private Channel Subscription RLS Execution Time report monitors the median time it takes to execute Row Level Security (RLS) policies when users publish messages to private channels. When a user sends a broadcast message to a private channel, Realtime checks RLS policies on the realtime.messages table to determine if the user has write (INSERT) access. This authorization check happens for the first message sent and then it is cached. Complex RLS policies with joins, function calls, or missing indexes can significantly increase first message publishing latency. Available for Pro, Team, and Enterprise plans.

Access token update event

The access_token event is used to setup a new token for Realtime authentication or to refresh the token to prevent a private channel from closing when the token expires. The payload contains `access_token` field with the new access token string.

Join errors and error codes

Join error categories: Auth-expired token (InvalidJWTExpiration, action: refresh token and rejoin), Auth-invalid token (MalformedJWT, JwtSignatureError, Unauthorized, action: do not retry), Rate limit (ConnectionRateLimitReached, ClientJoinRateLimitReached, ChannelRateLimitReached, action: backoff), Database (InitializingProjectConnection, IncreaseConnectionPool, DatabaseLackOfConnections, UnableToConnectToProject, action: exponential backoff), Config (TopicNameRequired, TenantNotFound, RealtimeDisabledForTenant, RealtimeDisabledForConfiguration, action: do not retry), Transient (RealtimeRestarting, action: backoff). Error format in phx_reply: response.reason as '<ErrorCode>: <human message>' except UnknownErrorOnChannel which is bare string.

Channel-level system errors

Channel-level system errors have extension 'system' and status 'error'. Messages and recovery: 'Too many messages per second' (broadcast rate limit, throttle sends), 'Too many presence messages per second' (presence rate limit, reduce frequency), 'Client presence rate limit exceeded' (per-client window, longer cooldown), 'Track message size exceeded' (payload too large, shrink), 'Token has expired' (JWT expired, refresh and rejoin), 'Fields role and exp are required in JWT' (fix token), 'Server requested disconnect' (reconnect after delay), 'Replication connection was not established in time' (when replication_ready requested, retry with backoff). All channel-level system errors are immediately followed by phx_close.

Access token refresh without rejoin

Refresh JWT in-band on private channels using access_token event without rejoining. Format: ['join_ref', 'ref', 'realtime:my-channel', 'access_token', { 'access_token': '<new-token>' }]. No reply on success. On failure, server emits system error and closes channel. Tokens with sb_* prefix are silently ignored.

Row Level Security with postgres_changes subscriptions

Row Level Security (RLS) must be enabled on tables to secure postgres_changes subscriptions. The documentation shows enabling RLS with: alter table "todos" enable row level security; Then create policies like: create policy "Allow anonymous access" on todos for select to anon using (true); RLS policies determine which database changes are visible to subscribers based on their role.

Give your agent this brain