• Stars
    star
    117
  • Rank 290,911 (Top 6 %)
  • Language PLpgSQL
  • License
    Apache License 2.0
  • Created over 2 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Applying RLS to PostgreSQL WAL

walrus

PostgreSQL version License


Source Code: https://github.com/supabase/walrus


Write Ahead Log Realtime Unified Security (WALRUS) is a utility for managing realtime subscriptions to tables and applying row level security rules to those subscriptions.

The subscription stream is based on logical replication slots.

Summary

Managing Subscriptions

User subscriptions are managed through a table

create table realtime.subscription (
    id bigint generated always as identity primary key,
    subscription_id uuid not null,
    entity regclass not null,
    filters realtime.user_defined_filter[] not null default '{}',
    claims jsonb not null,
    claims_role regrole not null generated always as (realtime.to_regrole(claims ->> 'role')) stored,
    created_at timestamp not null default timezone('utc', now()),

    unique (subscription_id, entity, filters)
);

where realtime.user_defined_filter is

create type realtime.user_defined_filter as (
    column_name text,
    op realtime.equality_op,
    value text
);

and realtime.equality_ops are a subset of postgrest ops. Specifically:

create type realtime.equality_op as enum(
    'eq', 'neq', 'lt', 'lte', 'gt', 'gte', 'in'
);

For example, to subscribe to a table named public.notes where the id is 6 as the authenticated role:

insert into realtime.subscription(subscription_id, entity, filters, claims)
values ('832bd278-dac7-4bef-96be-e21c8a0023c4', 'public.notes', array[('id', 'eq', '6')], '{"role", "authenticated"}');

Reading WAL

This package exposes 1 public SQL function realtime.apply_rls(jsonb). It processes the output of a wal2json decoded logical replication slot and returns:

  • wal: (jsonb) The WAL record as JSONB in the form
  • is_rls_enabled: (bool) If the entity (table) the WAL record represents has row level security enabled
  • subscription_ids: (uuid[]) An array subscription ids that should be notified about the WAL record
  • errors: (text[]) An array of errors

The jsonb WAL record is in the following format for inserts.

{
    "type": "INSERT",
    "schema": "public",
    "table": "todos",
    "columns": [
        {
            "name": "id",
            "type": "int8",
        },
        {
            "name": "details",
            "type": "text",
        },
        {
            "name": "user_id",
            "type": "int8",
        }
    ],
    "commit_timestamp": "2021-09-29T17:35:38Z",
    "record": {
        "id": 1,
        "user_id": 1,
        "details": "mow the lawn"
    }
}

updates:

{
    "type": "UPDATE",
    "schema": "public",
    "table": "todos",
    "columns": [
        {
            "name": "id",
            "type": "int8",
        },
        {
            "name": "details",
            "type": "text",
        },
        {
            "name": "user_id",
            "type": "int8",
        }
    ],
    "commit_timestamp": "2021-09-29T17:35:38Z",
    "record": {
        "id": 2,
        "user_id": 1,
        "details": "mow the lawn"
    },
    "old_record": {
        "id": 1,
    }
}

deletes:

{
    "type": "DELETE",
    "schema": "public",
    "table": "todos",
    "columns": [
        {
            "name": "id",
            "type": "int8",
        },
        {
            "name": "details",
            "type": "text",
        },
        {
            "name": "user_id",
            "type": "int8",
        }
    ],
    "old_record": {
        "id": 1
    }
}

Important Notes:

  • Row level security is not applied to delete statements
  • The key/value pairs displayed in the old_record field include the table's identity columns for the record being updated/deleted. To display all values in old_record set the replica identity for the table to full
  • When a delete occurs, the contents of old_record will be broadcast to all subscribers to that table so ensure that each table's replica identity only contains information that is safe to expose publicly

Error States

Error 400: Bad Request, no primary key

If a WAL record for a table that does not have a primary key is passed through realtime.apply_rls, an error is returned

Ex:

(
    {
        "type": ...,
        "schema": ...,
        "table": ...
    },                               -- wal
    true,                            -- is_rls_enabled
    [...],                           -- subscription_ids,
    array['Error 400: Bad Request, no primary key'] -- errors
)::realtime.wal_rls;

Error 401: Unauthorized

If a WAL record is passed through realtime.apply_rls and the subscription's clams_role does not have permission to select the primary key columns in that table, an Unauthorized error is returned with no WAL data.

Ex:

(
    {
        "type": ...,
        "schema": ...,
        "table": ...
    },                               -- wal
    true,                            -- is_rls_enabled
    [...],                           -- subscription_ids,
    array['Error 401: Unauthorized'] -- errors
)::realtime.wal_rls;

Error 413: Payload Too Large

When the size of the wal2json record exceeds max_record_bytes the record and old_record objects are filtered to include only fields with a value size <= 64 bytes. The errors output array is set to contain the string "Error 413: Payload Too Large".

Ex:

(
    {..., "record": {"id": 1}, "old_record": {"id": 1}}, -- wal
    true,                                  -- is_rls_enabled
    [...],                                 -- subscription_ids,
    array['Error 413: Payload Too Large']  -- errors
)::realtime.wal_rls;

How it Works

Each WAL record is passed into realtime.apply_rls(jsonb) which:

  • impersonates each subscribed user by setting the appropriate role and request.jwt.claims that RLS policies depend on
  • queries for the row using its primary key values
  • applies the subscription's filters to check if the WAL record is filtered out
  • filters out all columns that are not visible to the user's role

Usage

Given a wal2json replication slot with the name realtime

select * from pg_create_logical_replication_slot('realtime', 'wal2json')

A complete list of config options can be found here:

The stream can be polled with

select
    xyz.wal,
    xyz.is_rls_enabled,
    xyz.subscription_ids,
    xyz.errors
from
    pg_logical_slot_get_changes(
        'realtime', null, null,
        'include-pk', '1',
        'include-transaction', 'false',
        'include-timestamp', 'true',
        'include-type-oids', 'true',
        'write-in-chunks', 'true',
        'format-version', '2',
        'actions', 'insert,update,delete',
        'filter-tables', 'realtime.*'
    ),
    lateral (
        select
            x.wal,
            x.is_rls_enabled,
            x.subscription_ids,
            x.errors
        from
            realtime.apply_rls(data::jsonb) x(wal, is_rls_enabled, subcription_ids, errors)
    ) xyz
where
    xyz.subscription_ids[1] is not null

Or, if the stream should be filtered according to a publication:

with pub as (
    select
        concat_ws(
            ',',
            case when bool_or(pubinsert) then 'insert' else null end,
            case when bool_or(pubupdate) then 'update' else null end,
            case when bool_or(pubdelete) then 'delete' else null end
        ) as w2j_actions,
        coalesce(
            string_agg(
                realtime.quote_wal2json(format('%I.%I', schemaname, tablename)::regclass),
                ','
            ) filter (where ppt.tablename is not null and ppt.tablename not like '% %'),
            ''
        ) w2j_add_tables
    from
        pg_publication pp
        left join pg_publication_tables ppt
            on pp.pubname = ppt.pubname
    where
        pp.pubname = 'supabase_realtime'
    group by
        pp.pubname
    limit 1
),
w2j as (
    select
        x.*, pub.w2j_add_tables
    from
         pub,
         pg_logical_slot_get_changes(
            'realtime', null, null,
            'include-pk', '1',
            'include-transaction', 'false',
            'include-type-oids', 'true',
            'include-timestamp', 'true',
            'write-in-chunks', 'true',
            'format-version', '2',
            'actions', pub.w2j_actions,
            'add-tables', pub.w2j_add_tables
        ) x
)
select
    xyz.wal,
    xyz.is_rls_enabled,
    xyz.subscription_ids,
    xyz.errors
from
    w2j,
    realtime.apply_rls(
        wal := w2j.data::jsonb,
        max_record_bytes := 1048576
    ) xyz(wal, is_rls_enabled, subscription_ids, errors)
where
    w2j.w2j_add_tables <> ''
    and xyz.subscription_ids[1] is not null

Configuration

max_record_bytes

max_record_bytes (default 1 MiB): Controls the maximum size of a WAL record that will be emitted with complete record and old_record data. When the size of the wal2json record exceeds max_record_bytes the record and old_record objects are filtered to include only fields with a value size <= 64 bytes. The errors output array is set to contain the string "Error 413: Payload Too Large".

Ex:

realtime.apply_rls(wal := w2j.data::jsonb, max_record_bytes := 1024*1024) x(wal, is_rls_enabled, subscription_ids, errors)

Installation

The project is SQL only and can be installed by executing the contents of sql/walrus--0.1.sql in a database instance.

Tests

Requires

  • Postgres 13+
  • wal2json >= 53b548a29ebd6119323b6eb2f6013d7c5fe807ec

On a Mac:

Install postgres

brew install postgres

Install wal2json

git clone https://github.com/eulerto/wal2json.git
cd wal2json
git reset --hard 53b548a
make
make install

Run the tests, from the repo root.

./bin/installcheck

RFC Process

To open an request for comment (RFC), open a github issue against this repo and select the RFC template.

More Repositories

1

supabase

The open source Firebase alternative.
TypeScript
65,693
star
2

realtime

Broadcast, Presence, and Postgres Changes via WebSockets
Elixir
6,458
star
3

postgres_lsp

A Language Server for Postgres
Rust
3,073
star
4

supabase-js

An isomorphic Javascript client for Supabase. Query your Supabase database, subscribe to realtime events, upload and download files, browse typescript examples, invoke postgres functions via rpc, invoke supabase edge functions, query pgvector.
TypeScript
2,795
star
5

pg_graphql

GraphQL support for PostgreSQL
Rust
2,760
star
6

supavisor

A cloud-native, multi-tenant Postgres connection pooler.
Elixir
1,574
star
7

ui

Supabase UI Library
TypeScript
1,510
star
8

postgres

Unmodified Postgres with some useful plugins
Shell
1,265
star
9

index_advisor

PostgreSQL Index Advisor
PLpgSQL
1,263
star
10

auth

A JWT based API for managing users and issuing JWT tokens
Go
1,159
star
11

pg_jsonschema

PostgreSQL extension providing JSON Schema validation
Rust
929
star
12

postgrest-js

Isomorphic JavaScript client for PostgREST.
TypeScript
917
star
13

auth-helpers

A collection of framework specific Auth utilities for working with Supabase.
TypeScript
877
star
14

cli

Supabase CLI. Manage postgres migrations, run Supabase locally, deploy edge functions. Postgres backups. Generating types from your database schema.
Go
849
star
15

postgres-meta

A RESTful API for managing your Postgres. Fetch tables, add roles, and run queries
TypeScript
820
star
16

storage

S3 compatible object storage service that stores metadata in Postgres
TypeScript
640
star
17

supabase-flutter

Flutter integration for Supabase. This package makes it simple for developers to build secure and scalable products.
Dart
613
star
18

supa_audit

Generic Table Auditing
PLpgSQL
611
star
19

supabase-swift

A Swift client for Supabase
Swift
583
star
20

edge-runtime

A server based on Deno runtime, capable of running JavaScript, TypeScript, and WASM services.
Rust
557
star
21

stripe-sync-engine

Sync your Stripe account to you Postgres database.
TypeScript
457
star
22

wrappers

Postgres Foreign Data Wrapper development framework in Rust.
Rust
433
star
23

auth-ui

Pre-built Auth UI for React
TypeScript
405
star
24

supabase-dart

A Dart client for Supabase
Dart
402
star
25

pg_crdt

POC CRDT support in Postgres
Rust
372
star
26

dbdev

Database Package Registry for Postgres
PLpgSQL
329
star
27

auth-js

An isomorphic Javascript library for Supabase Auth.
CSS
298
star
28

realtime-js

An isomorphic Javascript client for Supabase Realtime server.
JavaScript
288
star
29

examples-archive

Supabase Examples Archive
TypeScript
278
star
30

pg_netstat

PostgreSQL extension to monitor database network traffic
Rust
246
star
31

grid

A react component to display your Postgresql table data. Used in Supabase Dashboard app.
TypeScript
197
star
32

vecs

Postgres/pgvector Python Client
Python
190
star
33

libcluster_postgres

Postgres strategy for libcluster
Elixir
178
star
34

pg_net

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL
PLpgSQL
165
star
35

vault

Extension for storing encrypted secrets in the Vault
PLpgSQL
161
star
36

postgrest-dart

Dart client for PostgREST
Dart
137
star
37

headless-vector-search

Supabase Toolkit to perform vector similarity search on your knowledge base embeddings.
TypeScript
135
star
38

workflows

Elixir
133
star
39

supabase-grafana

Observability for your Supabase project, using Prometheus/Grafana
Shell
132
star
40

storage-js

JS Client library to interact with Supabase Storage
TypeScript
111
star
41

postgres-deno

A PostgreSQL extension for Deno: run Typescript in PostgreSQL functions and triggers.
104
star
42

realtime-dart

A dart client for Supabase Realtime server.
Dart
85
star
43

setup-cli

A GitHub action for interacting with your Supabase projects using the CLI.
TypeScript
83
star
44

repository.surf

🏄
JavaScript
80
star
45

embeddings-generator

GitHub Action to generate embeddings from the markdown files in your repository.
TypeScript
79
star
46

supabase-ui-web

TypeScript
74
star
47

self-hosted-edge-functions-demo

A demo of how to self-host Supabase Edge Functions on Fly.io
TypeScript
61
star
48

functions-js

TypeScript
54
star
49

supabase-admin-api

API to administer the Supabase server (KPS)
Go
51
star
50

supautils

PostgreSQL extension that secures a cluster on a cloud environment
C
49
star
51

gotrue-dart

A dart client library for GoTrue.
Dart
47
star
52

supabase-action-example

TypeScript
45
star
53

benchmarks

SCSS
41
star
54

grafana-agent-fly-example

Deploy a Grafana Agent on Fly to scrape Prometheus metrics from Supabase and send them to Grafana Cloud
Shell
36
star
55

functions-relay

API Gateway for Supabase Edge functions
TypeScript
35
star
56

nix-postgres

Experimental port of supabase/postgres to Nix
Nix
35
star
57

benchmarks-archive

Infrastucture benchmarks
Nix
31
star
58

hibp

Go library for HaveIBeenPwned.org's pwned passwords API.
Go
29
star
59

splinter

Supabase Postgres Linter
PLpgSQL
28
star
60

supabase.ai

iykyk
HTML
27
star
61

storage-dart

Dart client library to interact with Supabase Storage
Dart
22
star
62

livebooks

A collection of Elixir Livebooks for Supabase
Dockerfile
20
star
63

base64url-js

Pure TypeScript implementation of Base64-URL encoding for JavaScript strings.
TypeScript
19
star
64

terraform-provider-supabase

Go
17
star
65

orb-sync-engine

TypeScript
12
star
66

.github

Org-wide default community health files & templates.
11
star
67

auth-elements

Components to add Supabase Auth to any application
TypeScript
11
star
68

rfcs

11
star
69

functions-dart

Dart
8
star
70

test-reports

Repository to store test reports data and host reporting in gh-pages
7
star
71

plug_caisson

An Elixir Plug library for handling compressed requests
Elixir
6
star
72

flyswatter

Deploy a global pinger on Fly
Elixir
6
star
73

scoop-bucket

4
star
74

tests

TypeScript
4
star
75

pgextkit

Rust
3
star
76

homebrew-tap

Ruby
3
star
77

fly-preview

TypeScript
3
star
78

shared-types

TypeScript
3
star
79

supa_type

The Missing PostgreSQL Data Types
Nix
3
star
80

test-inspector

Check your test results against the reference run and compare coverage for multiple client libraries
Go
2
star
81

mailme

A clone of Netlify's mailme package used in Supabase Auth / GoTrue.
Go
2
star
82

productions

Supabase SynthWave. The best soundtrack to build an app in a weekend and scale to billions.
TypeScript
1
star
83

design-tokens

1
star