# Supabase RLS & RPC Security Auditor MCP (`pabloian92/mcp-supabase-rls-auditor`) Actor

Deterministic MCP server auditing Supabase SQL migrations & client code for missing RLS, permissive policies, SECURITY DEFINER search_path bugs, orphaned RPCs, and leaked secrets (/mcp).

- **URL**: https://apify.com/pabloian92/mcp-supabase-rls-auditor.md
- **Developed by:** [Pablo Ian Laurino](https://apify.com/pabloian92) (community)
- **Categories:** AI, Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $50.00 / 1,000 supabase rls & rpc security audits

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Supabase RLS & RPC Security Auditor MCP

An Apify Standby MCP server for Supabase projects. It serves one deterministic tool over Streamable HTTP at `/mcp` that statically audits SQL migrations and client code for RLS gaps, `SECURITY DEFINER` function issues, orphaned RPC calls, and exposed secrets. It reads only the data supplied in each call and makes no network changes.

### Tool

| Tool | Input | Output | Event price |
| --- | --- | --- | ---: |
| `supabase_rls_audit` | `project_path`: path to project directory inside container | Summary counts, detailed findings with fixes, and formatted report | $0.05 |

#### Rules Checked

| Rule ID | Severity | Title |
| --- | --- | --- |
| `RLS-001` | CRITICAL | Public table has RLS disabled |
| `RLS-002` | HIGH | Policy grants unrestricted access |
| `RPC-001` | HIGH | `SECURITY DEFINER` function lacks search path or authorization guard |
| `RPC-002` | HIGH | Frontend calls a missing RPC function |
| `SEC-001` | CRITICAL | Potential secret exposed in client material |

The audit uses only standard-library Python (no runtime deps beyond the MCP/Apify SDKs). It parses SQL files for `CREATE TABLE`, `ALTER TABLE ... ENABLE ROW LEVEL SECURITY`, `CREATE POLICY`, `CREATE FUNCTION`, and `DROP FUNCTION` statements. It scans client source files (TypeScript/JavaScript/React under `src/`) for `.rpc()` calls and secret patterns (`SUPABASE_SERVICE_ROLE_KEY`, `VITE_*_SECRET`, `VITE_*_SERVICE_ROLE`, JWTs).

### Run locally

Requires Python 3.11+.

```sh
pip install -e .
python -m pytest tests/
python -m src.main
```

The server listens on `ACTOR_WEB_SERVER_PORT` or port 3000 and provides `GET /health`. For a local billing simulation, set `ACTOR_TEST_PAY_PER_EVENT=true` before starting. Local calls without this variable are unbilled. On Apify, each successfully returned tool result calls `Actor.charge` once; a charge failure or exhausted spending limit prevents the result from being returned. Invalid arguments are not charged.

#### Example MCP client configuration after deployment

```json
{
  "mcpServers": {
    "supabase-rls-auditor": {
      "url": "https://YOUR-STANDBY-URL.apify.actor/mcp",
      "headers": { "Authorization": "Bearer YOUR_APIFY_API_TOKEN" }
    }
  }
}
```

#### Example arguments

```json
{
  "project_path": "/app/project",
  "format": "json",
  "fail_on": "critical"
}
```

The project directory should be mounted or copied into the container at the specified path. The audit scans:

- All `.sql` files (migrations) for RLS, policies, and RPC functions
- `.env.example` at the project root
- Client files under `src/` with extensions `.ts`, `.tsx`, `.js`, `.jsx`

### Deploy and monetize

1. Push with `apify push` from this directory. `.actor/actor.json` enables Standby and exposes `/mcp`.
2. In Apify Console, set the Actor pricing model to **Pay per event** and verify the event name and USD price in `.actor/pay_per_event.json`. Apify documents an 80% creator share of PPE event revenue; applicable platform costs and terms affect the final payout. The code does not set a payout percentage.
3. Set a sensible per-run spending limit and test the tool through the Standby URL with an Apify token. Apify authenticates the public Standby URL; the container HTTP server relies on that proxy and should not be exposed directly to the public internet.

The Docker image installs locked production dependencies and runs as an unprivileged user. The service is stateless, so multiple Standby instances can serve calls independently.

### Local testing with a sample project

```sh
## Create a test project structure
mkdir -p /tmp/test-project/supabase/migrations /tmp/test-project/src

## Add a migration with issues
cat > /tmp/test-project/supabase/migrations/001_init.sql <<'EOF'
CREATE TABLE public.profiles (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id uuid REFERENCES auth.users(id),
    name text
);
-- Missing: ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Public read" ON public.profiles FOR SELECT USING (true);

CREATE FUNCTION public.get_user_profile(user_id uuid)
RETURNS json LANGUAGE sql SECURITY DEFINER AS $$
    SELECT json_build_object('id', id, 'name', name) FROM public.profiles WHERE user_id = get_user_profile.user_id;
$$;
-- Missing: SET search_path = public, pg_temp AND auth.uid() guard
EOF

## Add client code with issues
cat > /tmp/test-project/src/api.ts <<'EOF'
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(
    process.env.SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!  // SEC-001: Service role key in client
)
supabase.rpc('get_user_profile', { user_id: '...' })  // RPC-002 if function missing
supabase.rpc('missing_function', {})  // RPC-002: orphaned call
EOF

## Run the auditor locally (unbilled)
ACTOR_TEST_PAY_PER_EVENT=true python -m src.main &
sleep 2
curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"supabase_rls_audit","arguments":{"project_path":"/tmp/test-project","format":"json"}}}'
```

### Limitations

- Static analysis only — no live database connection, no query execution, no runtime policy evaluation.
- SQL parsing handles common patterns but is not a full PostgreSQL parser; complex statements (CTEs, dollar-quoted bodies, nested functions) may be missed.
- Client scanning is limited to `src/` directories and common file extensions; monorepo structures may need path adjustment.
- `RPC-002` only reports calls to functions not seen in scanned SQL; functions created outside scanned migrations (e.g., via Supabase Dashboard) will be false positives.
- Secret detection is pattern-based; false positives/negatives possible. Always rotate any credential that was committed.

### License

MIT — see the [LICENSE](LICENSE) file if present.

# Actor input Schema

## `mode` (type: `string`):

Keep 'standby' to expose the Streamable HTTP MCP server at /mcp.

## Actor input object example

```json
{
  "mode": "standby"
}
```

# Actor output Schema

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("pabloian92/mcp-supabase-rls-auditor").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("pabloian92/mcp-supabase-rls-auditor").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call pabloian92/mcp-supabase-rls-auditor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,pabloian92/mcp-supabase-rls-auditor"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/rsb2XvjRpNcy8gU2s/builds/m2ZAgBaKPu6taHQub/openapi.json
