Supabase Policy Guardrails
Overview
Organizational governance for Supabase at scale: a shared RLS policy library (reusable templates for common access patterns), naming conventions (tables, columns, functions, policies), migration review process (CI checks ensuring RLS, preventing destructive operations, enforcing naming), cost alert configuration (billing thresholds and usage monitoring), and security audit scripts (scanning for exposed keys, missing RLS, overly permissive policies). All patterns use real createClient from @supabase/supabase-js and Supabase CLI commands.
Prerequisites
- Supabase project with
supabase CLI installed and linked
@supabase/supabase-js v2+ installed
- CI/CD pipeline (GitHub Actions recommended)
- Database access via
psql or Supabase SQL Editor
- Pro plan recommended for cost alerts and usage API
Step 1 — Shared RLS Policy Library and Naming Conventions
RLS Policy Templates
Create reusable RLS policy templates that teams apply to new tables. This prevents each developer from writing ad-hoc policies and ensures consistent access control.
-- supabase/migrations/00000000000000_rls_policy_library.sql
-- Shared RLS policy library — apply these templates to new tables
-- ============================================================
-- Template 1: Owner-only access (user owns the row)
-- Usage: tables with a user_id column (todos, profiles, settings)
-- ============================================================
CREATE OR REPLACE FUNCTION public.rls_owner_only(table_name text, user_column text DEFAULT 'user_id')
RETURNS void AS $$
BEGIN
EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', table_name);
EXECUTE format(
'CREATE POLICY "owner_select" ON public.%I FOR SELECT USING (%I = auth.uid())',
table_name, user_column
);
EXECUTE format(
'CREATE POLICY "owner_insert" ON public.%I FOR INSERT WITH CHECK (%I = auth.uid())',
table_name, user_column
);
EXECUTE format(
'CREATE POLICY "owner_update" ON public.%I FOR UPDATE USING (%I = auth.uid())',
table_name, user_column
);
EXECUTE format(
'CREATE POLICY "owner_delete" ON public.%I FOR DELETE USING (%I = auth.uid())',
table_name, user_column
);
END;
$$ LANGUAGE plpgsql;
-- ============================================================
-- Template 2: Organization-scoped access (user is member of org)
-- Usage: tables with org_id referencing org_members
-- ============================================================
CREATE OR REPLACE FUNCTION public.rls_org_scoped(
table_name text,
org_column text DEFAULT 'org_id',
allow_delete boolean DEFAULT false
)
RETURNS void AS $$
BEGIN
EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', table_name);
EXECUTE format(
'CREATE POLICY "org_select" ON public.%I FOR SELECT USING (
%I IN (SELECT org_id FROM public.org_members WHERE user_id = auth.uid())
)', table_name, org_column
);
EXECUTE format(
'CREATE POLICY "org_insert" ON public.%I FOR INSERT WITH CHECK (
%I IN (SELECT org_id FROM public.org_members WHERE user_id = auth.uid())
)', table_name, org_column
);
EXECUTE format(
'CREATE POLICY "org_update" ON public.%I FOR UPDATE USING (
%I IN (SELECT org_id FROM public.org_members WHERE user_id = auth.uid() AND role IN (''admin'', ''editor''))
)', table_name, org_column
);
IF allow_delete THEN
EXECUTE format(
'CREATE POLICY "org_delete" ON public.%I FOR DELETE USING (
%I IN (SELECT org_id FROM public.org_members WHERE user_id = auth.uid() AND role = ''admin'')
)', table_name, org_column
);
END IF;
END;
$$ LANGUAGE plpgsql;
-- ============================================================
-- Template 3: Public read, authenticated write
-- Usage: blog posts, product listings, public content
-- ============================================================
CREATE OR REPLACE FUNCTION public.rls_public_read_auth_write(
table_name text,
owner_column text DEFAULT 'created_by'
)
RETURNS void AS $$
BEGIN
EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', table_name);
EXECUTE format(
'CREATE POLICY "public_select" ON public.%I FOR SELECT USING (true)',
table_name
);
EXECUTE format(
'CREATE POLICY "auth_insert" ON public.%I FOR INSERT WITH CHECK (auth.uid() IS NOT NULL)',
table_name
);
EXECUTE format(
'CREATE POLICY "owner_update" ON public.%I FOR UPDATE USING (%I = auth.uid())',
table_name, owner_column
);
EXECUTE format(
'CREATE POLICY "owner_delete" ON public.%I FOR DELETE USING (%I = auth.uid())',
table_name, owner_column
);
END;
$$ LANGUAGE plpgsql;
-- Apply templates to tables:
-- SELECT public.rls_owner_only('todos');
-- SELECT public.rls_org_scoped('projects', 'org_id', true);
-- SELECT public.rls_public_read_auth_write('blog_posts', 'author_id');
Naming Conventions
-- supabase/migrations/00000000000001_naming_convention_check.sql
-- Validation function that checks naming conventions at migration time
CREATE OR REPLACE FUNCTION public.validate_naming_conventions()
RETURNS TABLE(issue text, object_name text, suggestion text) AS $$
BEGIN
-- Tables must be snake_case, plural
RETURN QUERY
SELECT
'Table name should be plural snake_case'::text,
t.tablename::text,
regexp_replace(t.tablename, '([A-Z])', '_\1', 'g')::text
FROM pg_tables t
WHERE t.schemaname = 'public'
AND (
t.tablename ~ '[A-Z]' -- contains uppercase
OR t.tablename ~ '-' -- contains hyphens
OR t.tablename !~ 's$' -- not plural (heuristic)
)
AND t.tablename NOT LIKE '\_%'; -- skip internal tables
-- Columns must be snake_case
RETURN QUERY
SELECT
'Column name should be snake_case'::text,
(c.table_name || '.' || c.column_name)::text,
regexp_replace(c.column_name, '([A-Z])', '_\1', 'g')::text
FROM information_schema.columns c
WHERE c.table_schema = 'public'
AND (c.column_name ~ '[A-Z]' OR c.column_name ~ '-');
-- Foreign key columns should end with _id
RETURN QUERY
SELECT
'Foreign key column should end with _id'::text,
(tc.table_name || '.' || kcu.column_name)::text,
(kcu.column_name || '_id')::text
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
WHERE tc.constraint_type = 'FOREIGN KEY'
AND tc.table_schema = 'public'
AND kcu.column_name NOT LIKE '%_id';
-- Boolean columns should start with is_ or has_
RETURN QUERY
SELECT
'Boolean column should start with is_ or has_'::text,
(c.table_name || '.' || c.column_name)::text,
('is_' || c.column_name)::text
FROM information_schema.columns c
WHERE c.table_schema = 'public'
AND c.data_type = 'boolean'
AND c.column_name NOT LIKE 'is_%'
AND c.column_name NOT LIKE 'has_%';
END;
$$ LANGUAGE plpgsql;
-- Run: SELECT * FROM public.validate_naming_conventions();
Naming Convention Reference
| Object |
Convention |
Example |
| Tables |
Plural snake_case |
user_profiles, order_items |
| Columns |
snake_case |
created_at, full_name |
| Foreign keys |
{referenced_table_singular}_id |
user_id, order_id |
| Booleans |
is_ or has_ prefix |
is_active, has_verified_email |
| Timestamps |
_at suffix |
created_at, updated_at, deleted_at |
| RLS policies |
{scope}_{operation} |
owner_select, org_insert |
| Functions |
verb_noun |
create_user, get_dashboard_metrics |
| Indexes |
idx_{table}_{columns} |
idx_orders_user_id_created_at |
| Migrations |
{timestamp}_{verb}_{description} |
20250322000000_create_orders_table.sql |
Step 2 — Migration Review Process with CI Checks
See CI checks, cost alerts, and security audits for GitHub Actions migration guardrails (RLS enforcement, naming checks, destructive operation blocks), pre-commit hooks, cost monitoring with Slack alerts, security audit scripts, and scheduled Edge Function audits.
Output
- Shared RLS policy library with owner-only, org-scoped, and public-read templates
- Naming convention validation function checking tables, columns, FKs, and booleans
- CI pipeline enforcing RLS, naming, and destructive operation controls
- Pre-commit hook blocking hardcoded secrets and tables without RLS
- Cost monitoring script with configurable thresholds and Slack alerting
- Security audit script detecting missing RLS, permissive policies, and missing indexes
- Scheduled Edge Function for continuous security monitoring
Error Handling
| Issue |
Cause |
Solution |
| CI RLS check fails on new table |
Migration missing ENABLE ROW LEVEL SECURITY |
Add ALTER TABLE after CREATE TABLE in same migration |
| Naming convention false positive |
Table is intentionally singular (e.g., config) |
Add to exclusion list in validation function |
| Cost alert not firing |
Missing SUPABASE_ACCESS_TOKEN |
Generate token at supabase.com/dashboard/account/tokens |
| Security audit times out |
Too many tables to scan |
Run audit on specific schemas or paginate results |
| Pre-commit blocks legitimate JWT in test |
Test fixture contains JWT-like string |
Add test file path to exclusion pattern |
| RLS template function not found |
Migration not applied |
Run supabase db reset or apply migration manually |
Examples
See CI, cost, and security reference for full examples including applying RLS templates, running security audits, and checking naming conventions.
Resources
Next Steps
For architecture patterns across different app types, see supabase-architecture-variants.
1---
2name: supabase-policy-guardrails
3description: |
4 Enforce organizational governance for Supabase projects: shared RLS policy
5 library with reusable templates, table and column naming conventions,
6 migration review process with CI checks, cost alert thresholds,
7 and security audit scripts scanning for common misconfigurations.
8 Use when establishing Supabase standards across teams, creating RLS
9 policy templates, setting up migration review workflows, or auditing
10 existing projects for security and cost issues.
11 Trigger with phrases like "supabase governance", "supabase policy library",
12 "supabase naming convention", "supabase migration review",
13 "supabase cost alert", "supabase security audit", "supabase RLS template".
14allowed-tools: Read, Write, Edit, Bash(supabase:*), Bash(psql:*), Bash(npx:*), Grep
15version: 1.0.0
16license: MIT
17author: Jeremy Longshore <jeremy@intentsolutions.io>
18compatible-with: claude-code, codex, openclaw
19tags: [saas, supabase, governance, security, rls, naming-conventions, cost-management]
20metadata:
21 source: https://skillmd.com/skills/aibot88/supabase-policy-guardrails
22---
23
24# Supabase Policy Guardrails
25
26## Overview
27
28Organizational governance for Supabase at scale: a **shared RLS policy library** (reusable templates for common access patterns), **naming conventions** (tables, columns, functions, policies), **migration review process** (CI checks ensuring RLS, preventing destructive operations, enforcing naming), **cost alert configuration** (billing thresholds and usage monitoring), and **security audit scripts** (scanning for exposed keys, missing RLS, overly permissive policies). All patterns use real `createClient` from `@supabase/supabase-js` and Supabase CLI commands.
29
30## Prerequisites
31
32- Supabase project with `supabase` CLI installed and linked
33- `@supabase/supabase-js` v2+ installed
34- CI/CD pipeline (GitHub Actions recommended)
35- Database access via `psql` or Supabase SQL Editor
36- Pro plan recommended for cost alerts and usage API
37
38## Step 1 — Shared RLS Policy Library and Naming Conventions
39
40### RLS Policy Templates
41
42Create reusable RLS policy templates that teams apply to new tables. This prevents each developer from writing ad-hoc policies and ensures consistent access control.
43
44```sql
45-- supabase/migrations/00000000000000_rls_policy_library.sql
46-- Shared RLS policy library — apply these templates to new tables
47
48-- ============================================================
49-- Template 1: Owner-only access (user owns the row)
50-- Usage: tables with a user_id column (todos, profiles, settings)
51-- ============================================================
52CREATE OR REPLACE FUNCTION public.rls_owner_only(table_name text, user_column text DEFAULT 'user_id')
53RETURNS void AS $$
54BEGIN
55 EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', table_name);
56
57 EXECUTE format(
58 'CREATE POLICY "owner_select" ON public.%I FOR SELECT USING (%I = auth.uid())',
59 table_name, user_column
60 );
61 EXECUTE format(
62 'CREATE POLICY "owner_insert" ON public.%I FOR INSERT WITH CHECK (%I = auth.uid())',
63 table_name, user_column
64 );
65 EXECUTE format(
66 'CREATE POLICY "owner_update" ON public.%I FOR UPDATE USING (%I = auth.uid())',
67 table_name, user_column
68 );
69 EXECUTE format(
70 'CREATE POLICY "owner_delete" ON public.%I FOR DELETE USING (%I = auth.uid())',
71 table_name, user_column
72 );
73END;
74$$ LANGUAGE plpgsql;
75
76-- ============================================================
77-- Template 2: Organization-scoped access (user is member of org)
78-- Usage: tables with org_id referencing org_members
79-- ============================================================
80CREATE OR REPLACE FUNCTION public.rls_org_scoped(
81 table_name text,
82 org_column text DEFAULT 'org_id',
83 allow_delete boolean DEFAULT false
84)
85RETURNS void AS $$
86BEGIN
87 EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', table_name);
88
89 EXECUTE format(
90 'CREATE POLICY "org_select" ON public.%I FOR SELECT USING (
91 %I IN (SELECT org_id FROM public.org_members WHERE user_id = auth.uid())
92 )', table_name, org_column
93 );
94 EXECUTE format(
95 'CREATE POLICY "org_insert" ON public.%I FOR INSERT WITH CHECK (
96 %I IN (SELECT org_id FROM public.org_members WHERE user_id = auth.uid())
97 )', table_name, org_column
98 );
99 EXECUTE format(
100 'CREATE POLICY "org_update" ON public.%I FOR UPDATE USING (
101 %I IN (SELECT org_id FROM public.org_members WHERE user_id = auth.uid() AND role IN (''admin'', ''editor''))
102 )', table_name, org_column
103 );
104
105 IF allow_delete THEN
106 EXECUTE format(
107 'CREATE POLICY "org_delete" ON public.%I FOR DELETE USING (
108 %I IN (SELECT org_id FROM public.org_members WHERE user_id = auth.uid() AND role = ''admin'')
109 )', table_name, org_column
110 );
111 END IF;
112END;
113$$ LANGUAGE plpgsql;
114
115-- ============================================================
116-- Template 3: Public read, authenticated write
117-- Usage: blog posts, product listings, public content
118-- ============================================================
119CREATE OR REPLACE FUNCTION public.rls_public_read_auth_write(
120 table_name text,
121 owner_column text DEFAULT 'created_by'
122)
123RETURNS void AS $$
124BEGIN
125 EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', table_name);
126
127 EXECUTE format(
128 'CREATE POLICY "public_select" ON public.%I FOR SELECT USING (true)',
129 table_name
130 );
131 EXECUTE format(
132 'CREATE POLICY "auth_insert" ON public.%I FOR INSERT WITH CHECK (auth.uid() IS NOT NULL)',
133 table_name
134 );
135 EXECUTE format(
136 'CREATE POLICY "owner_update" ON public.%I FOR UPDATE USING (%I = auth.uid())',
137 table_name, owner_column
138 );
139 EXECUTE format(
140 'CREATE POLICY "owner_delete" ON public.%I FOR DELETE USING (%I = auth.uid())',
141 table_name, owner_column
142 );
143END;
144$$ LANGUAGE plpgsql;
145
146-- Apply templates to tables:
147-- SELECT public.rls_owner_only('todos');
148-- SELECT public.rls_org_scoped('projects', 'org_id', true);
149-- SELECT public.rls_public_read_auth_write('blog_posts', 'author_id');
150```
151
152### Naming Conventions
153
154```sql
155-- supabase/migrations/00000000000001_naming_convention_check.sql
156-- Validation function that checks naming conventions at migration time
157
158CREATE OR REPLACE FUNCTION public.validate_naming_conventions()
159RETURNS TABLE(issue text, object_name text, suggestion text) AS $$
160BEGIN
161 -- Tables must be snake_case, plural
162 RETURN QUERY
163 SELECT
164 'Table name should be plural snake_case'::text,
165 t.tablename::text,
166 regexp_replace(t.tablename, '([A-Z])', '_\1', 'g')::text
167 FROM pg_tables t
168 WHERE t.schemaname = 'public'
169 AND (
170 t.tablename ~ '[A-Z]' -- contains uppercase
171 OR t.tablename ~ '-' -- contains hyphens
172 OR t.tablename !~ 's$' -- not plural (heuristic)
173 )
174 AND t.tablename NOT LIKE '\_%'; -- skip internal tables
175
176 -- Columns must be snake_case
177 RETURN QUERY
178 SELECT
179 'Column name should be snake_case'::text,
180 (c.table_name || '.' || c.column_name)::text,
181 regexp_replace(c.column_name, '([A-Z])', '_\1', 'g')::text
182 FROM information_schema.columns c
183 WHERE c.table_schema = 'public'
184 AND (c.column_name ~ '[A-Z]' OR c.column_name ~ '-');
185
186 -- Foreign key columns should end with _id
187 RETURN QUERY
188 SELECT
189 'Foreign key column should end with _id'::text,
190 (tc.table_name || '.' || kcu.column_name)::text,
191 (kcu.column_name || '_id')::text
192 FROM information_schema.table_constraints tc
193 JOIN information_schema.key_column_usage kcu
194 ON tc.constraint_name = kcu.constraint_name
195 WHERE tc.constraint_type = 'FOREIGN KEY'
196 AND tc.table_schema = 'public'
197 AND kcu.column_name NOT LIKE '%_id';
198
199 -- Boolean columns should start with is_ or has_
200 RETURN QUERY
201 SELECT
202 'Boolean column should start with is_ or has_'::text,
203 (c.table_name || '.' || c.column_name)::text,
204 ('is_' || c.column_name)::text
205 FROM information_schema.columns c
206 WHERE c.table_schema = 'public'
207 AND c.data_type = 'boolean'
208 AND c.column_name NOT LIKE 'is_%'
209 AND c.column_name NOT LIKE 'has_%';
210END;
211$$ LANGUAGE plpgsql;
212
213-- Run: SELECT * FROM public.validate_naming_conventions();
214```
215
216### Naming Convention Reference
217
218| Object | Convention | Example |
219|--------|-----------|---------|
220| Tables | Plural snake_case | `user_profiles`, `order_items` |
221| Columns | snake_case | `created_at`, `full_name` |
222| Foreign keys | `{referenced_table_singular}_id` | `user_id`, `order_id` |
223| Booleans | `is_` or `has_` prefix | `is_active`, `has_verified_email` |
224| Timestamps | `_at` suffix | `created_at`, `updated_at`, `deleted_at` |
225| RLS policies | `{scope}_{operation}` | `owner_select`, `org_insert` |
226| Functions | `verb_noun` | `create_user`, `get_dashboard_metrics` |
227| Indexes | `idx_{table}_{columns}` | `idx_orders_user_id_created_at` |
228| Migrations | `{timestamp}_{verb}_{description}` | `20250322000000_create_orders_table.sql` |
229
230## Step 2 — Migration Review Process with CI Checks
231
232See [CI checks, cost alerts, and security audits](references/ci-cost-security.md) for GitHub Actions migration guardrails (RLS enforcement, naming checks, destructive operation blocks), pre-commit hooks, cost monitoring with Slack alerts, security audit scripts, and scheduled Edge Function audits.
233
234## Output
235
236- Shared RLS policy library with owner-only, org-scoped, and public-read templates
237- Naming convention validation function checking tables, columns, FKs, and booleans
238- CI pipeline enforcing RLS, naming, and destructive operation controls
239- Pre-commit hook blocking hardcoded secrets and tables without RLS
240- Cost monitoring script with configurable thresholds and Slack alerting
241- Security audit script detecting missing RLS, permissive policies, and missing indexes
242- Scheduled Edge Function for continuous security monitoring
243
244## Error Handling
245
246| Issue | Cause | Solution |
247|-------|-------|----------|
248| CI RLS check fails on new table | Migration missing `ENABLE ROW LEVEL SECURITY` | Add `ALTER TABLE` after `CREATE TABLE` in same migration |
249| Naming convention false positive | Table is intentionally singular (e.g., `config`) | Add to exclusion list in validation function |
250| Cost alert not firing | Missing `SUPABASE_ACCESS_TOKEN` | Generate token at supabase.com/dashboard/account/tokens |
251| Security audit times out | Too many tables to scan | Run audit on specific schemas or paginate results |
252| Pre-commit blocks legitimate JWT in test | Test fixture contains JWT-like string | Add test file path to exclusion pattern |
253| RLS template function not found | Migration not applied | Run `supabase db reset` or apply migration manually |
254
255## Examples
256
257See [CI, cost, and security reference](references/ci-cost-security.md) for full examples including applying RLS templates, running security audits, and checking naming conventions.
258
259## Resources
260
261- [Supabase Row Level Security](https://supabase.com/docs/guides/database/postgres/row-level-security)
262- [Supabase CLI Migrations](https://supabase.com/docs/guides/cli/managing-environments)
263- [Supabase Management API](https://supabase.com/docs/reference/api/introduction)
264- [Supabase Pricing](https://supabase.com/pricing)
265- [PostgreSQL Naming Conventions](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS)
266
267## Next Steps
268
269For architecture patterns across different app types, see `supabase-architecture-variants`.