Repository navigation
feat(supabase): Supabase PostgREST integration module for auth:byo #149
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
dc8ad2e
feat(supabase): add Supabase PostgREST integration module for auth:byo
pyramation a61e41b
fix(supabase): allow service roles to invoke pre-request hook
pyramation 9e72944
fix(supabase): declare verification plan dependencies
pyramation 62a2c84
fix(supabase): grant hook execution despite secure defaults
pyramation 1afb9fc
refactor(supabase-integration): rename package to avoid @pgpm/supabas…
pyramation a33e24b
refactor(supabase): name the integration @pgpm/supabase at 1.0.0
pyramation 737d4b3
ci(supabase): isolate Supabase CI in its own workflow
pyramation File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| name: Supabase integration | ||
| on: | ||
| push: | ||
| branches: | ||
| - main | ||
| paths: | ||
| - 'packages/supabase/**' | ||
| - '.github/workflows/supabase.yml' | ||
| pull_request: | ||
| paths: | ||
| - 'packages/supabase/**' | ||
| - '.github/workflows/supabase.yml' | ||
| workflow_dispatch: | ||
|
|
||
| jobs: | ||
| supabase: | ||
| runs-on: ubuntu-latest | ||
|
|
||
| env: | ||
| PGHOST: localhost | ||
| PGPORT: 5432 | ||
| PGUSER: postgres | ||
| PGPASSWORD: password | ||
| PGPM_VERSION: 5.18.0 | ||
|
|
||
| services: | ||
| pg_db: | ||
| image: constructiveio/postgres-plus:18 | ||
| env: | ||
| POSTGRES_USER: postgres | ||
| POSTGRES_PASSWORD: password | ||
| options: >- | ||
| --health-cmd "pg_isready -U postgres" | ||
| --health-interval 10s | ||
| --health-timeout 5s | ||
| --health-retries 5 | ||
| ports: | ||
| - 5432:5432 | ||
|
|
||
| steps: | ||
| - name: Configure Git (for tests) | ||
| run: | | ||
| git config --global user.name "CI Test User" | ||
| git config --global user.email "ci@example.com" | ||
|
|
||
| - name: Checkout | ||
| uses: actions/checkout@v4 | ||
|
|
||
| - name: Setup pnpm | ||
| uses: pnpm/action-setup@v2 | ||
| with: | ||
| version: 9 | ||
|
|
||
| - name: Setup Node.js | ||
| uses: actions/setup-node@v4 | ||
| with: | ||
| node-version: '20' | ||
| cache: 'pnpm' | ||
|
|
||
| - name: Install | ||
| run: pnpm install | ||
|
|
||
| - name: Cache pgpm CLI | ||
| uses: actions/cache@v4 | ||
| with: | ||
| path: ~/.npm | ||
| key: pgpm-${{ env.PGPM_VERSION }} | ||
|
|
||
| - name: Install pgpm CLI globally | ||
| run: npm install -g pgpm@${{ env.PGPM_VERSION }} | ||
|
|
||
| - name: Tune Postgres for CI (disable durability) | ||
| run: pgpm tune --yes | ||
|
|
||
| - name: Seed Supabase users | ||
| run: | | ||
| pgpm admin-users bootstrap --client --yes | ||
| pgpm admin-users add --test --yes | ||
| psql -v ON_ERROR_STOP=1 -c 'CREATE ROLE anon NOINHERIT NOLOGIN;' | ||
|
|
||
| - name: Test Supabase | ||
| run: pnpm --dir packages/supabase test | ||
|
|
||
| - name: Full cycle for Supabase only | ||
| run: | | ||
| excludes=$(find packages -name '*.control' ! -path 'packages/supabase/*' -printf '%f\n' | sed 's/\.control$//' | paste -sd, -) | ||
| pgpm test-packages --full-cycle --exclude "$excludes" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| __tests__ | ||
| jest.config.js |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| The MIT License (MIT) | ||
|
|
||
| Copyright (c) 2025 Dan Lynch <pyramation@gmail.com> | ||
| Copyright (c) 2025 Constructive | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| EXTENSION = pgpm-supabase | ||
| DATA = sql/pgpm-supabase--1.0.0.sql | ||
|
|
||
| PG_CONFIG = pg_config | ||
| PGXS := $(shell $(PG_CONFIG) --pgxs) | ||
| include $(PGXS) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| # @pgpm/supabase | ||
|
|
||
| Bridge Supabase PostgREST requests to Constructive's transaction-local RLS claims. | ||
|
|
||
| ## Supabase setup | ||
|
|
||
| 1. Run `pgpm admin-users bootstrap --yes` against the Supabase database to create | ||
| Constructive's `anonymous` role (and the other base roles). | ||
| 2. Ensure Supabase's `anon` and `authenticated` roles already exist. Outside | ||
| Supabase, create `anon` with `CREATE ROLE anon NOINHERIT NOLOGIN;` before deployment. | ||
| 3. Install `@pgpm/supabase` and deploy `pgpm-supabase` with `pgpm deploy`. | ||
| 4. As the database administrator, configure PostgREST: | ||
|
|
||
| ```sql | ||
| ALTER ROLE authenticator SET pgrst.db_pre_request = 'supabase_integration.pre_request'; | ||
| NOTIFY pgrst, 'reload config'; | ||
| ``` | ||
|
|
||
| Schema USAGE and hook EXECUTE are available to PUBLIC so PostgREST can also | ||
| invoke the hook as `service_role` without requiring that role at deploy time. | ||
| The hook is a no-op for roles other than `anon` and `authenticated`. | ||
|
|
||
| The security-invoker hook switches `anon` to `anonymous`. It does not grant | ||
| automatic inheritance: `anon` cannot use `anonymous` grants without switching. | ||
| On PostgreSQL 16+ the membership explicitly disables inheritance and allows SET; | ||
| on PostgreSQL 15 it relies on Supabase's `anon` being NOINHERIT. | ||
|
|
||
| For `authenticated`, the hook copies the verified `request.jwt.claims` JSON `sub` | ||
| to both `jwt.claims.user_id` and `jwt.claims.principal_id`, transaction-locally. | ||
| The subject must correspond to Constructive's `users.id`. Missing/empty claims | ||
| or subjects leave the claims unset; malformed JSON raises an error. Other roles | ||
| are unchanged. Only use this hook behind PostgREST's verified JWT boundary; | ||
| it does not verify JWTs or provision users. Each request must use a fresh transaction. | ||
|
|
||
| RLS policies must treat empty claim strings as absent, for example | ||
| `nullif(current_setting('jwt.claims.user_id', true), '')::uuid`. PostgreSQL can | ||
| return an empty string for a custom GUC after its transaction-local value is | ||
| rolled back; a direct UUID cast would then raise on a later unauthenticated request. | ||
|
|
||
| ## Development | ||
|
|
||
| ```sh | ||
| eval "$(pgpm env)" | ||
| pnpm test | ||
| pgpm package | ||
| ``` | ||
|
|
||
| The tests create a missing `anon` role before deploying the module. Reverting | ||
| revokes the membership and drops the hook and schema, but does not drop roles | ||
| or change PostgREST configuration. Remove the pre-request setting before reverting. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import { getConnections, PgTestClient } from 'pgsql-test'; | ||
| import { seed } from 'pgsql-test/seed'; | ||
|
|
||
| let pg: PgTestClient; | ||
| let teardown: () => Promise<void>; | ||
| const userId = '00000000-0000-0000-0000-000000000001'; | ||
| const otherId = '00000000-0000-0000-0000-000000000002'; | ||
|
|
||
| beforeAll(async () => { | ||
| ({ pg, teardown } = await getConnections({}, [ | ||
| seed.fn(async ({ pg }) => { | ||
| await pg.query(` | ||
| DO $$ BEGIN | ||
| IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'anon') THEN | ||
| CREATE ROLE anon NOINHERIT NOLOGIN; | ||
| END IF; | ||
| END $$; | ||
| `); | ||
| }), | ||
| seed.pgpm() | ||
| ])); | ||
| await pg.query(` | ||
| CREATE TABLE public.anonymous_read (value text); | ||
| INSERT INTO public.anonymous_read VALUES ('public content'); | ||
| GRANT SELECT ON public.anonymous_read TO anonymous; | ||
| CREATE TABLE public.owned_rows (user_id uuid PRIMARY KEY); | ||
| INSERT INTO public.owned_rows VALUES ('${userId}'), ('${otherId}'); | ||
| ALTER TABLE public.owned_rows ENABLE ROW LEVEL SECURITY; | ||
| GRANT SELECT ON public.owned_rows TO authenticated; | ||
| CREATE POLICY own_rows ON public.owned_rows TO authenticated | ||
| USING (user_id = nullif(current_setting('jwt.claims.user_id', true), '')::uuid); | ||
| `); | ||
| }); | ||
|
|
||
| afterAll(async () => { await teardown?.(); }); | ||
| beforeEach(async () => { | ||
| pg.setContext({ role: null, 'request.jwt.claims': null }); | ||
| await pg.beforeEach(); | ||
| }); | ||
| afterEach(async () => { await pg.afterEach(); }); | ||
|
|
||
| async function preRequestThen(sql: string) { | ||
| const results: any = await pg.query(`SELECT supabase_integration.pre_request(); ${sql}`); | ||
| return results[1].rows; | ||
| } | ||
|
|
||
| it('does not inherit anonymous grants before pre_request', async () => { | ||
| pg.setContext({ role: 'anon' }); | ||
| await pg.expectError(() => pg.query('SELECT * FROM public.anonymous_read'), /permission denied/); | ||
| }); | ||
|
|
||
| it('switches anon to anonymous and reads anonymous grants', async () => { | ||
| pg.setContext({ role: 'anon' }); | ||
| expect(await preRequestThen('SELECT current_user, value FROM public.anonymous_read')) | ||
| .toEqual([{ current_user: 'anonymous', value: 'public content' }]); | ||
| }); | ||
|
|
||
| it('bridges both identity claims and restricts rows to the subject', async () => { | ||
| pg.setContext({ role: 'authenticated', 'request.jwt.claims': JSON.stringify({ sub: userId }) }); | ||
| expect(await preRequestThen(`SELECT user_id, | ||
| current_setting('jwt.claims.user_id', true) AS claim, | ||
| current_setting('jwt.claims.principal_id', true) AS principal | ||
| FROM public.owned_rows`)).toEqual([{ user_id: userId, claim: userId, principal: userId }]); | ||
| }); | ||
|
|
||
| it.each([null, '', '{}', '{"sub":""}'])('handles absent subject in claims %p', async claims => { | ||
| pg.setContext({ role: 'authenticated', 'request.jwt.claims': claims }); | ||
| expect(await preRequestThen('SELECT * FROM public.owned_rows')).toEqual([]); | ||
| }); | ||
|
|
||
| it('does nothing for other roles', async () => { | ||
| pg.setContext({ role: null, 'request.jwt.claims': JSON.stringify({ sub: userId }) }); | ||
| expect(await preRequestThen(`SELECT current_user = session_user AS unchanged, | ||
| nullif(current_setting('jwt.claims.user_id', true), '') AS claim`)) | ||
| .toEqual([{ unchanged: true, claim: null }]); | ||
| }); | ||
|
|
||
| it('allows a role with no grants to call the hook as a no-op', async () => { | ||
| await pg.query('CREATE ROLE supabase_test_service NOINHERIT NOLOGIN'); | ||
| pg.setContext({ role: 'supabase_test_service', 'request.jwt.claims': JSON.stringify({ sub: userId }) }); | ||
| expect(await preRequestThen(`SELECT current_user, | ||
| nullif(current_setting('jwt.claims.user_id', true), '') AS claim, | ||
| nullif(current_setting('jwt.claims.principal_id', true), '') AS principal`)) | ||
| .toEqual([{ current_user: 'supabase_test_service', claim: null, principal: null }]); | ||
| }); | ||
|
|
||
| it('rejects malformed JWT JSON', async () => { | ||
| pg.setContext({ role: 'authenticated', 'request.jwt.claims': 'invalid' }); | ||
| await pg.expectError(() => pg.query('SELECT supabase_integration.pre_request()'), /invalid input syntax for type json/); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| -- Deploy roles/anon to pg | ||
|
|
||
| BEGIN; | ||
|
|
||
| DO $$ | ||
| BEGIN | ||
| IF current_setting('server_version_num')::integer >= 160000 THEN | ||
| GRANT anonymous TO anon WITH INHERIT FALSE, SET TRUE; | ||
| ELSE | ||
| GRANT anonymous TO anon; | ||
| END IF; | ||
| END; | ||
| $$; | ||
|
|
||
| COMMIT; |
26 changes: 26 additions & 0 deletions
26
packages/supabase/deploy/schemas/supabase_integration/procedures/pre_request.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| -- Deploy schemas/supabase_integration/procedures/pre_request to pg | ||
|
|
||
| BEGIN; | ||
|
|
||
| CREATE FUNCTION supabase_integration.pre_request() | ||
| RETURNS void | ||
| LANGUAGE plpgsql | ||
| AS $$ | ||
| DECLARE | ||
| subject text; | ||
| BEGIN | ||
| IF current_user = 'anon' THEN | ||
| PERFORM set_config('role', 'anonymous', true); | ||
| ELSIF current_user = 'authenticated' THEN | ||
| subject := nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub'; | ||
| IF subject IS NOT NULL AND subject <> '' THEN | ||
| PERFORM set_config('jwt.claims.user_id', subject, true); | ||
| PERFORM set_config('jwt.claims.principal_id', subject, true); | ||
| END IF; | ||
| END IF; | ||
| END; | ||
| $$; | ||
|
|
||
| GRANT EXECUTE ON FUNCTION supabase_integration.pre_request() TO PUBLIC; | ||
|
|
||
| COMMIT; |
9 changes: 9 additions & 0 deletions
9
packages/supabase/deploy/schemas/supabase_integration/schema.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| -- Deploy schemas/supabase_integration/schema to pg | ||
|
|
||
| BEGIN; | ||
|
|
||
| CREATE SCHEMA supabase_integration; | ||
|
|
||
| GRANT USAGE ON SCHEMA supabase_integration TO PUBLIC; | ||
|
|
||
| COMMIT; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| /** @type {import('ts-jest').JestConfigWithTsJest} */ | ||
| module.exports = { | ||
| forceExit: true, | ||
| preset: 'ts-jest', | ||
| testEnvironment: 'node', | ||
|
|
||
| // Match both __tests__ and colocated test files | ||
| testMatch: ['**/?(*.)+(test|spec).{ts,tsx,js,jsx}'], | ||
|
|
||
| // Ignore build artifacts and type declarations | ||
| testPathIgnorePatterns: ['/dist/', '\\.d\\.ts$'], | ||
| modulePathIgnorePatterns: ['<rootDir>/dist/'], | ||
| watchPathIgnorePatterns: ['/dist/'], | ||
|
|
||
| moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| { | ||
| "name": "@pgpm/supabase", | ||
| "version": "1.0.0", | ||
| "description": "Bridge Supabase PostgREST requests to Constructive RLS claims", | ||
| "author": "Dan Lynch <pyramation@gmail.com>", | ||
| "contributors": [ | ||
| "Constructive <developers@constructive.io>" | ||
| ], | ||
| "keywords": [ | ||
| "postgresql", | ||
| "pgpm", | ||
| "supabase", | ||
| "authentication" | ||
| ], | ||
| "publishConfig": { | ||
| "access": "public" | ||
| }, | ||
| "scripts": { | ||
| "bundle": "pgpm package", | ||
| "test": "jest", | ||
| "test:watch": "jest --watch" | ||
| }, | ||
| "devDependencies": { | ||
| "pgpm": "^5", | ||
| "pgsql-test": "^5.20.13" | ||
| }, | ||
| "dependencies": { | ||
| "@pgpm/verify": "workspace:*" | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "https://github.com/constructive-io/pgpm-modules" | ||
| }, | ||
| "homepage": "https://github.com/constructive-io/pgpm-modules", | ||
| "bugs": { | ||
| "url": "https://github.com/constructive-io/pgpm-modules/issues" | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| # pgpm-supabase extension | ||
| comment = 'Supabase PostgREST integration for Constructive' | ||
| default_version = '1.0.0' | ||
| module_pathname = '$libdir/pgpm-supabase' | ||
| requires = 'plpgsql,pgpm-verify' | ||
| relocatable = false | ||
| superuser = false |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Publish the module as
@pgpm/supabase-integration.The manifest name
@pgpm/supabasedoes not match the name the PR gives this module. The PR states that@pgpm/supabaseis already used by the vendored Supabase platform schema. Publishing under this name can fail or target another package. Consumers then cannot install this release under the intended name.Change the manifest name. Update the README references to the same name.
Suggested fix
Committable suggestion