HIGH api key exposuresupabase

Api Key Exposure on Supabase

How Api Key Exposure Manifests in Supabase

API key exposure in Supabase applications typically occurs through several distinct patterns that are unique to the Supabase architecture. Understanding these specific attack vectors is critical for securing your Supabase applications.

The most common scenario involves service_role keys being committed to public repositories. Supabase generates two types of API keys: anon_public (for unauthenticated users) and service_role (for administrative operations). Service_role keys have elevated privileges including unrestricted database access and row-level security bypass. When developers accidentally commit these keys to GitHub or npm packages, attackers immediately gain full database control.

Another Supabase-specific exposure pattern occurs in Next.js applications where environment variables are improperly handled. During build time, Next.js can embed environment variables into client-side bundles if they're not properly prefixed with NEXT_PUBLIC_. This means a .env file containing SUPABASE_SERVICE_ROLE_KEY becomes accessible to any user viewing the application's source code.

Client-side JavaScript code often directly embeds API keys in fetch requests:

const supabase = createClient(
  'https://your-project.supabase.co',
  process.env.SUPABASE_SERVICE_ROLE_KEY // Exposed to browser
);

This pattern is particularly dangerous because the service_role key provides complete database access, allowing attackers to read, modify, or delete any data without authentication.

Third-party integrations also create exposure risks. Many Supabase users integrate with authentication providers, analytics services, or third-party APIs that require API keys. These keys often get logged in browser consoles, network tab requests, or third-party service dashboards, creating multiple potential exposure points.

Supply chain attacks represent another Supabase-specific vector. Malicious npm packages can scan for and exfiltrate Supabase credentials from package.json files, configuration files, or environment variables during installation or runtime.

Supabase-Specific Detection

Detecting API key exposure in Supabase applications requires both automated scanning and manual code review. middleBrick's API security scanner includes specialized detection for Supabase-specific patterns.

middleBrick scans for exposed API keys by testing endpoints for authentication bypass attempts. For Supabase applications, it specifically looks for:

  • Service_role key usage in client-side code
  • Anonymous access to restricted endpoints
  • Missing row-level security policies
  • Excessive database permissions

The scanner tests authentication endpoints by attempting requests without credentials and with minimal permissions, identifying BOLA (Broken Object Level Authorization) vulnerabilities that often accompany API key exposure.

Manual detection techniques include:

# Search for exposed keys in your codebase
rg "service_role|anon_public" --type js --type ts --type json

# Check for embedded keys in built files
find dist -name "*.js" -exec grep -l "supabase" {} \;

# Verify environment variable usage in Next.js
next build 2>&1 | grep -E "(SUPABASE|service_role)"

Supabase provides built-in security scanning through their dashboard. Navigate to Authentication > Settings > API to view all active keys and their usage patterns. Any service_role key appearing in client applications indicates a critical security issue.

Network monitoring can reveal exposed keys through HTTP request analysis. Tools like browser developer tools or Wireshark can capture API calls to identify whether service_role keys are being transmitted to client browsers.

middleBrick's LLM security scanning also detects prompt injection attacks that could exploit exposed API keys in AI-powered applications. This includes scanning for system prompt leakage and testing for jailbreak attempts that might reveal credential storage patterns.

Supabase-Specific Remediation

Remediating API key exposure in Supabase requires architectural changes and strict key management practices. The fundamental principle is never exposing service_role keys to client applications.

Implement proper key separation by using only anon_public keys in client applications:

// Client-side: Only use anon_public key
const supabase = createClient(
  'https://your-project.supabase.co',
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
);

// Server-side: Use service_role key securely
import { createClient } from '@supabase/supabase-js';

const supabaseAdmin = createClient(
  'https://your-project.supabase.co',
  process.env.SUPABASE_SERVICE_ROLE_KEY
);

export async function getSensitiveData() {
  const { data, error } = await supabaseAdmin
    .from('users')
    .select('*');
  return { data, error };
}

Enable Row Level Security (RLS) to prevent unauthorized data access even if keys are compromised:

-- Enable RLS on critical tables
ALTER TABLE users ENABLE ROW LEVEL SECURITY;

-- Create policies for authenticated users
CREATE POLICY "Users can view own profile"
  ON users
  FOR SELECT
  USING (auth.uid() = id);

-- Restrict service_role to specific operations
CREATE POLICY "Service role can manage users"
  ON users
  FOR ALL
  TO authenticated
  USING (auth.role() = 'service_role');

Implement API Gateway protection for Supabase endpoints:

// Next.js API route with key validation
export default async function handler(req, res) {
  // Validate API key before proxying to Supabase
  const apiKey = req.headers['x-api-key'];
  if (!isValidServiceKey(apiKey)) {
    return res.status(401).json({ error: 'Invalid API key' });
  }
  
  // Proxy request to Supabase
  const supabaseResponse = await fetch(
    `https://your-project.supabase.co/rest/v1/${req.query.table}`,
    {
      method: req.method,
      headers: {
        ...req.headers,
        'apikey': apiKey,
      },
      body: req.body,
    }
  );
  
  return res.status(supabaseResponse.status).json(await supabaseResponse.json());
}

Use middleBrick's continuous monitoring to detect when new API keys are exposed in your codebase. The Pro plan automatically scans your APIs on a configurable schedule, alerting you when security scores drop below your threshold.

Implement environment-specific key management using Supabase's project organization features. Create separate Supabase projects for development, staging, and production, each with appropriately restricted keys. This limits the blast radius if keys are exposed in non-production environments.

Regularly audit your Supabase projects through the dashboard, reviewing active keys and their last usage timestamps. Revoke any unused or suspicious keys immediately. middleBrick's compliance reports map your API security posture to frameworks like OWASP API Top 10 and PCI-DSS, helping you maintain regulatory compliance.

Frequently Asked Questions

Can I use the same Supabase service_role key across multiple applications?
No, using the same service_role key across multiple applications creates significant security risks. Each application should have its own Supabase project with appropriately scoped keys. Service_role keys provide unrestricted database access, so sharing them increases the attack surface and makes it impossible to track which application might have exposed the key. Use anon_public keys for client applications and keep service_role keys restricted to server-side operations only.
How does middleBrick detect API key exposure in Supabase applications?
middleBrick performs black-box scanning of your Supabase endpoints, testing for authentication bypass and privilege escalation vulnerabilities. It specifically looks for service_role key usage patterns, attempts to access restricted endpoints without authentication, and tests for missing row-level security policies. The scanner runs 12 security checks in parallel, including authentication testing and data exposure analysis, providing a security risk score (A-F) with prioritized findings and remediation guidance. For LLM-powered Supabase applications, it also tests for prompt injection vulnerabilities that could expose credential storage patterns.