Security Documentation

    Comprehensive guide to security best practices, RLS policies, and edge function patterns

    Row Level Security (RLS) Policies

    What is RLS?

    Row Level Security is a PostgreSQL feature that restricts which rows users can access in database tables. RLS policies are evaluated for every query, providing fine-grained access control at the database level.

    Correct Implementation

    -- Enable RLS on the table
    ALTER TABLE public.appointments ENABLE ROW LEVEL SECURITY;
    
    -- Admin users can view all appointments
    CREATE POLICY "Only admins can view appointments"
      ON public.appointments
      FOR SELECT
      USING (has_role(auth.uid(), 'admin'::app_role));
    
    -- Users can view their own data
    CREATE POLICY "Users can view their own data"
      ON public.user_profiles
      FOR SELECT
      USING (auth.uid() = user_id);

    Common Mistakes

    ❌ Infinite Recursion

    -- WRONG: Queries same table in policy
    CREATE POLICY "Admin access"
      ON public.profiles
      USING (
        (SELECT role FROM public.profiles 
         WHERE id = auth.uid()) = 'admin'
      );

    This causes infinite recursion. Use a security definer function instead.

    ❌ Missing RLS on Sensitive Tables

    Always enable RLS on tables containing PII or sensitive data. Anonymous users should NOT have read access to user emails, phone numbers, or personal information.

    ❌ Overly Permissive Policies

    -- WRONG: Allows anyone to read everything
    CREATE POLICY "Public read"
      ON public.sensitive_data
      FOR SELECT
      USING (true);

    Security Definer Functions

    Use SECURITY DEFINER functions to avoid recursive RLS issues:

    CREATE OR REPLACE FUNCTION public.has_role(
      _user_id uuid, 
      _role app_role
    )
    RETURNS boolean
    LANGUAGE sql
    STABLE
    SECURITY DEFINER
    SET search_path = public
    AS $$
      SELECT EXISTS (
        SELECT 1
        FROM public.user_roles
        WHERE user_id = _user_id
          AND role = _role
      )
    $$;

    Edge Function Security Patterns

    JWT Verification

    By default, edge functions require JWT authentication. Only disable for public endpoints:

    # supabase/config.toml
    [functions.public-endpoint]
    verify_jwt = false  # Only for public APIs!
    
    [functions.admin-endpoint]
    # verify_jwt = true (default - KEEP THIS)
    Warning

    Disabling JWT verification means anyone can call the endpoint. Implement your own validation!

    Environment Variables for Secrets

    Correct Pattern

    // ✅ Use environment variables
    const apiKey = Deno.env.get('API_KEY');
    
    // ✅ Server-side feature flags
    const debugMode = Deno.env.get('ENABLE_DEBUG_MODE') === 'true';
    
    // ❌ Never hardcode secrets
    // const apiKey = 'sk-abc123...';
    
    // ❌ Never trust client headers alone
    // const isDebug = req.headers.get('x-debug') === 'true';

    Avoid Raw SQL Execution

    ❌ Never Execute Raw SQL

    // WRONG - SQL injection risk
    const { data } = await supabase
      .rpc('execute_sql', { 
        query: `SELECT * FROM users WHERE email = '${email}'`
      });

    ✅ Use Supabase Client Methods

    // CORRECT - Parameterized and safe
    const { data } = await supabase
      .from('users')
      .select()
      .eq('email', email);

    Authentication & Authorization

    Role-Based Access Control

    -- Create role enum
    CREATE TYPE public.app_role AS ENUM ('admin', 'moderator', 'user');
    
    -- User roles table (NEVER store roles in profiles table!)
    CREATE TABLE public.user_roles (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      user_id uuid REFERENCES auth.users(id) ON DELETE CASCADE NOT NULL,
      role app_role NOT NULL,
      UNIQUE (user_id, role)
    );

    Critical Security Warnings

    ❌ Never Check Admin Status Client-Side

    // WRONG - Can be manipulated
    const isAdmin = localStorage.getItem('isAdmin') === 'true';
    
    // WRONG - Hardcoded credentials
    if (email === 'admin@example.com' && password === 'admin123') {

    Always use server-side validation with Supabase auth and RLS policies.

    ✅ Correct Admin Check

    // Client: Query with RLS enforcement
    const { data: roles } = await supabase
      .from('user_roles')
      .select('role')
      .eq('user_id', user.id);
    
    const isAdmin = roles?.some(r => r.role === 'admin');

    Input Validation

    Always Validate Server-Side

    Never trust client-side validation alone. Use schema validation libraries like zod:

    import { z } from "https://deno.land/x/zod@v3.22.4/mod.ts";
    
    const formDataSchema = z.object({
      name: z.string()
        .trim()
        .min(2, "Name must be at least 2 characters")
        .max(100, "Name must be less than 100 characters")
        .regex(/^[a-zA-Z\s\-'.]+$/, "Invalid characters"),
      email: z.string()
        .trim()
        .toLowerCase()
        .email("Invalid email address")
        .max(255),
      projectDescription: z.string()
        .trim()
        .min(10, "Description too short")
        .max(5000, "Description too long")
    });
    
    // Validate before processing
    const result = formDataSchema.safeParse(formData);
    if (!result.success) {
      return new Response(
        JSON.stringify({ 
          error: 'Invalid input',
          details: result.error.errors 
        }),
        { status: 400 }
      );
    }

    Sanitize All User Input

    • Never use dangerouslySetInnerHTML with user content
    • Validate email formats, phone numbers, URLs
    • Enforce length limits on all text fields
    • Use parameterized queries (Supabase client does this automatically)
    • Encode user input before using in URLs (use encodeURIComponent)

    CORS Configuration

    Never Use Wildcard CORS

    ❌ Insecure Pattern

    // WRONG - Allows any website to call your API
    const corsHeaders = {
      'Access-Control-Allow-Origin': '*'
    };

    ✅ Secure Pattern

    const ALLOWED_ORIGINS = [
      'https://yourdomain.com',
      'https://www.yourdomain.com'
    ];
    
    const getCorsHeaders = (origin: string) => {
      const isAllowed = ALLOWED_ORIGINS.includes(origin);
      
      if (!isAllowed) {
        return null; // Reject disallowed origins
      }
      
      return {
        'Access-Control-Allow-Origin': origin, // Return validated origin
        'Access-Control-Allow-Headers': 'authorization, content-type',
        'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
        'Vary': 'Origin' // Important for caching
      };
    };

    Error Handling & Information Disclosure

    Sanitize Error Messages

    Never expose internal system details, database errors, or configuration information to users.

    ❌ Insecure - Exposes Internals

    return new Response(
      JSON.stringify({ 
        error: 'Database connection failed',
        details: error.message,
        code: error.code,
        stack: error.stack
      }),
      { status: 500 }
    );

    ✅ Secure - Generic User Message

    // Log detailed error server-side
    console.error('Database error:', {
      code: error.code,
      message: error.message,
      stack: error.stack
    });
    
    // Return generic message to user
    return new Response(
      JSON.stringify({ 
        error: 'Unable to process your request. Please try again later.',
        success: false
      }),
      { status: 500 }
    );

    Rate Limiting

    Implement rate limiting on all public endpoints to prevent abuse:

    // Check rate limit before processing
    const { data: rateLimitData } = await supabase
      .from('rate_limits')
      .select('request_count, window_start')
      .eq('ip_address', clientIp)
      .eq('endpoint', 'verify-captcha')
      .maybeSingle();
    
    if (rateLimitData?.request_count >= 5) {
      return new Response(
        JSON.stringify({ 
          error: 'Rate limit exceeded. Please try again later.',
          success: false
        }),
        { status: 429 }
      );
    }

    Best Practices:

    • Use IP-based rate limiting for anonymous endpoints
    • Use user-based rate limiting for authenticated endpoints
    • Implement sliding window or token bucket algorithms
    • Set appropriate limits (e.g., 5 requests per hour for forms)
    • Clean up old rate limit records periodically

    Security Best Practices Checklist

    Database Security

    Enable RLS on all tables containing sensitive data
    Use security definer functions to avoid recursive RLS issues
    Store roles in separate table, never in user profiles
    Implement least-privilege access patterns

    Edge Function Security

    Keep JWT verification enabled except for public endpoints
    Use environment variables for all secrets and API keys
    Validate all user inputs with schema validation (zod)
    Implement proper CORS with allowed origin lists
    Sanitize error messages before returning to clients

    Application Security

    Never store sensitive data in localStorage or sessionStorage
    Implement rate limiting on all public endpoints
    Use HTTPS for all production traffic
    Regularly update dependencies and scan for vulnerabilities
    Log security events but never log passwords or tokens

    Note: This documentation reflects the current security implementation in this project. Always perform regular security audits and stay updated with the latest security best practices. For production applications handling sensitive data, consider professional security assessments.