supabase-security-basics

0
0
Source

Execute apply Supabase security best practices for secrets and access control. Use when securing API keys, implementing least privilege access, or auditing Supabase security configuration. Trigger with phrases like "supabase security", "supabase secrets", "secure supabase", "supabase API key security".

Install

mkdir -p .claude/skills/supabase-security-basics && curl -L -o skill.zip "https://mcp.directory/api/skills/download/7937" && unzip -o skill.zip -d .claude/skills/supabase-security-basics && rm skill.zip

Installs to .claude/skills/supabase-security-basics

About this skill

Supabase Security Basics

Overview

Supabase exposes a Postgres database directly to the internet via PostgREST. Every table without Row Level Security enabled is fully readable and writable by anyone with your project URL and anon key — both of which are public. This skill covers the three pillars of Supabase security: key separation (anon vs service_role), RLS policy enforcement, and API surface hardening.

Prerequisites

  • Supabase project created (local or hosted) with Dashboard access
  • @supabase/supabase-js installed (npm install @supabase/supabase-js)
  • SUPABASE_URL and SUPABASE_ANON_KEY environment variables configured
  • Basic understanding of SQL and Postgres

Instructions

Step 1 — Understand the Two API Keys

Supabase issues two keys per project. Confusing them is the most common security mistake:

KeyEnvironment VariableExposed to Client?RLS Behavior
Anon keySUPABASE_ANON_KEYYes — browser-safeRespects all RLS policies
Service role keySUPABASE_SERVICE_ROLE_KEYNEVER exposeBypasses ALL RLS

The anon key is a JWT that PostgREST uses to determine which RLS policies apply. It is safe to include in client-side bundles — it can only access data that RLS policies explicitly allow. The service role key bypasses every RLS policy and should only ever exist in server-side code (API routes, Edge Functions, cron jobs, migration scripts).

// CORRECT: anon key on the client
import { createClient } from '@supabase/supabase-js'

const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
)
// CORRECT: service role key ONLY in server-side code
// e.g., app/api/admin/route.ts (Next.js server route)
import { createClient } from '@supabase/supabase-js'

const supabaseAdmin = createClient(
  process.env.SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!,
  { auth: { autoRefreshToken: false, persistSession: false } }
)
// WRONG — service role key in client-side code
// This bypasses ALL RLS and leaks your admin key to every user
const supabase = createClient(url, process.env.NEXT_PUBLIC_SERVICE_ROLE_KEY!)  // NEVER DO THIS

Key rotation: Regenerate keys in Dashboard > Settings > API. After rotation, update every environment variable and redeploy all services. Old keys are invalidated immediately — there is no grace period.

Step 2 — Enforce Row Level Security on Every Table

Without RLS, any table in the public schema is fully accessible via the REST API to anyone holding the anon key. RLS is not optional — it is the primary access control layer.

-- Audit: find tables missing RLS
SELECT schemaname, tablename, rowsecurity
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY tablename;

-- Enable RLS on every public table
ALTER TABLE public.users ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.todos ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;

-- CRITICAL: enabling RLS with NO policies blocks ALL access via the API.
-- You MUST add at least one policy per table per operation (SELECT, INSERT, UPDATE, DELETE).

Policy pattern — users read/write their own rows:

-- SELECT: user can only read their own rows
CREATE POLICY "Users read own data"
  ON public.todos FOR SELECT
  USING (auth.uid() = user_id);

-- INSERT: user can only insert rows for themselves
CREATE POLICY "Users insert own data"
  ON public.todos FOR INSERT
  WITH CHECK (auth.uid() = user_id);

-- UPDATE: user can only update their own rows
CREATE POLICY "Users update own data"
  ON public.todos FOR UPDATE
  USING (auth.uid() = user_id)
  WITH CHECK (auth.uid() = user_id);

-- DELETE: user can only delete their own rows
CREATE POLICY "Users delete own data"
  ON public.todos FOR DELETE
  USING (auth.uid() = user_id);

Policy pattern — public read, authenticated write:

CREATE POLICY "Anyone can read posts"
  ON public.posts FOR SELECT
  USING (true);

CREATE POLICY "Authenticated users can insert"
  ON public.posts FOR INSERT
  WITH CHECK (auth.uid() IS NOT NULL);

Policy pattern — role-based access via custom JWT claims:

-- Admin-only policy using app_metadata
CREATE POLICY "Admins have full access"
  ON public.settings FOR ALL
  USING (
    (auth.jwt() -> 'app_metadata' ->> 'role') = 'admin'
  );

To set custom claims server-side:

// Server-side only — requires service role key
const { error } = await supabaseAdmin.auth.admin.updateUserById(userId, {
  app_metadata: { role: 'admin' }
})

Policy pattern — organization-scoped access:

CREATE POLICY "Org members can read projects"
  ON public.projects FOR SELECT
  USING (
    EXISTS (
      SELECT 1 FROM public.members
      WHERE members.organization_id = projects.organization_id
      AND members.user_id = auth.uid()
    )
  );

Key distinction — USING vs WITH CHECK:

  • USING (expr) — filters which existing rows the user can see (SELECT, UPDATE, DELETE)
  • WITH CHECK (expr) — validates new/modified row data (INSERT, UPDATE)
  • For UPDATE, you need both: USING controls which rows can be targeted, WITH CHECK controls what the new values can be

Step 3 — Harden the API Surface

JWT verification: Supabase verifies JWTs server-side automatically. The auth.uid() function in RLS policies extracts the authenticated user's ID from the verified JWT. You do not need to verify tokens manually in RLS policies — Supabase handles this.

SQL injection prevention: The Supabase JS SDK uses parameterized queries internally. Never build raw SQL strings from user input — always use the SDK query builder:

// SAFE: SDK parameterizes automatically
const { data } = await supabase
  .from('posts')
  .select('*')
  .eq('author_id', userId)
  .ilike('title', `%${searchTerm}%`)

// DANGEROUS: raw SQL with string interpolation
// Only use supabase.rpc() with parameterized functions, never template literals

Network restrictions: Restrict direct database connections to known IP ranges in Dashboard > Settings > Database > Network Restrictions. This does not affect the REST API (which goes through PostgREST) but protects direct Postgres connections.

CORS configuration: Configure allowed origins per project in Dashboard > Settings > API > CORS. Default allows all origins (*) — restrict to your domains in production.

Disable unused auth providers: Dashboard > Authentication > Providers. Disable any provider you are not actively using (email, phone, Google, GitHub, etc.) to reduce attack surface.

SSL enforcement: Dashboard > Settings > Database > SSL Configuration. Enforce SSL for all direct database connections.

Statement timeouts: Prevent long-running queries from exhausting database resources:

ALTER ROLE authenticated SET statement_timeout = '10s';
ALTER ROLE anon SET statement_timeout = '5s';

Revoke default schema grants (verify only):

-- Supabase handles this by default, but verify:
-- anon and authenticated roles should only access data through RLS policies
SELECT grantee, privilege_type, table_name
FROM information_schema.role_table_grants
WHERE table_schema = 'public'
AND grantee IN ('anon', 'authenticated')
ORDER BY table_name, grantee;

Output

After completing these steps you will have:

  • Anon key used exclusively in client-side code, service role key restricted to server-side
  • RLS enabled on every public table with explicit policies per operation
  • Custom JWT claims configured for role-based access patterns
  • Network restrictions, CORS, SSL, and statement timeouts hardened
  • Unused auth providers disabled

Security Audit Checklist

  • RLS enabled on ALL public tables (SELECT rowsecurity FROM pg_tables WHERE schemaname='public')
  • Every table has at least one RLS policy per needed operation
  • Service role key is NOT in any client-side or NEXT_PUBLIC_* environment variables
  • .env files are in .gitignore
  • Email confirmation enabled (Dashboard > Authentication > Settings)
  • OAuth redirect URLs restricted to your domains
  • Unused auth providers disabled
  • SSL enforcement enabled (Dashboard > Database > SSL)
  • Database password changed from default
  • Network restrictions configured for direct DB connections
  • statement_timeout set for authenticated and anon roles
  • MFA enabled for sensitive user operations
  • Point-in-time recovery (PITR) enabled for production
  • API keys rotated after any suspected exposure

Error Handling

ErrorCauseSolution
42501: new row violates row-level security policyRLS policy missing or WITH CHECK condition failsAdd or fix the RLS policy for that operation; verify auth.uid() matches the row's user column
Query returns empty data with no errorRLS USING clause filters out all rowsVerify auth.uid() in the policy matches the authenticated user; check JWT claims
PGRST301: JWSErrorInvalid or expired JWT tokenRe-authenticate the user; verify SUPABASE_ANON_KEY matches the project
PGRST302: anonymous access disabledAnon key not provided in client initPass the anon key to createClient(); check environment variable is set
permission denied for table XRLS enabled but no matching policyCreate a policy for the specific operation (SELECT/INSERT/UPDATE/DELETE)
Could not find the function auth.uid()Running SQL outside PostgREST contextauth.uid() only works in RLS policies evaluated by PostgREST; use explicit user IDs in migrations

Examples

Minimal secure setup for a new table:

-- 1. Create table
CREATE TABLE public.notes (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  user_id UUID REFERENCES auth.users(id) NOT NULL DEFAULT aut

---

*Content truncated.*

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

7824

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

13615

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

3114

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

4311

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

109

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

1128

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

9521,094

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

846846

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

571699

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

548492

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

673466

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

514280

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.