Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Tighten SQL execution in the MCP server

François Zaninotto431a9568810a
diff --git a/supabase/functions/mcp/index.ts b/supabase/functions/mcp/index.ts
index e0a56297..35bf6af0 100644
--- a/supabase/functions/mcp/index.ts
+++ b/supabase/functions/mcp/index.ts
@@ -1,3 +1,45 @@
+// Atomic CRM MCP server.
+//
+// Exposes the CRM database to AI assistants over the Model Context Protocol.
+// The `query` and `mutate` tools execute SQL written by the model, so the
+// security of this function rests on constraining what that SQL can do. The
+// enforcement is layered; each layer holds on its own:
+//
+// 1. Authentication: `withSupabase({ auth: "user" })` verifies the caller's
+// token against the project JWKS. Anonymous callers never reach a tool.
+//
+// 2. Identity and RLS: every statement runs in its own transaction (see
+// rlsPostgres.ts) that injects the caller's claims and drops to the
+// `authenticated` role, exactly like PostgREST. Row Level Security and
+// table grants then apply as they do in the application. No other role is
+// ever assumed: a token naming another role is refused before any query.
+//
+// 3. SQL validator (validateSql.ts): a single statement per call, SELECT/WITH
+// for `query`, INSERT/UPDATE/DELETE for `mutate`, no `set_config()` (it
+// could rewrite the claims or the role mid-statement), and schema-qualified
+// function calls restricted to `public`, `pg_catalog` and `auth`. It walks
+// the raw AST so no syntactic position escapes it (DISTINCT ON and OVER
+// once did).
+//
+// 4. Postgres as the backstop for what the validator cannot know:
+// - `SET LOCAL search_path = public`: the `http` (extensions schema) and
+// `pg_net` (net schema) functions let a query make the database issue
+// HTTP requests, i.e. an SSRF primitive. Their EXECUTE grants cannot be
+// revoked from a migration (they are owned by supabase_admin), so they
+// are kept off the search_path instead: an unqualified `http_get(...)`
+// does not resolve, whatever the validator did.
+// - `SET TRANSACTION READ ONLY` for `query`: a SELECT that calls a volatile
+// function (merge_contacts, the pg_net request queue...) cannot write.
+// - `SET LOCAL statement_timeout`: the connection logs in as `postgres`,
+// so the `authenticated` role's own timeout does not apply; a
+// `pg_sleep()` cannot hold a pooled connection for long.
+//
+// Consequence worth knowing: with `extensions` off the search_path, the
+// `citext` operators are not visible either, so `=` on citext columns
+// (companies.website, sales.email) is case-sensitive in this tool. The tool
+// descriptions tell the model to use ILIKE or lower(), and get_schema reports
+// those columns as `citext` rather than `USER-DEFINED`.
+
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import {
createMcpHandler,
@@ -9,15 +51,10 @@ import {
withOAuthProtectedResource,
withSupabase,
} from "npm:@supabase/[email protected]";
-import {
- withPostgresClient,
- type PostgresApi,
-} from "npm:@supabase/[email protected]/middleware/postgres";
-// pg is an optional peer dependency of @supabase/server, required by
-// withPostgresClient: importing it puts it in the module graph.
import pg from "npm:[email protected]";
import { z } from "npm:zod@^4.3.6";
import { validateReadOnly, validateWrite } from "./validateSql.ts";
+import { createRlsPostgres, type RlsPostgres } from "./rlsPostgres.ts";
import { TASK_LIST_HTML, TASK_LIST_UI_URI } from "./taskListUi.ts";
const CRM_BASE_URL = (Deno.env.get("CRM_BASE_URL") ?? "").replace(/\/$/, "");
@@ -26,17 +63,38 @@ const CRM_BASE_URL = (Deno.env.get("CRM_BASE_URL") ?? "").replace(/\/$/, "");
// model can pass ids straight back to the tools that expect integers.
pg.types.setTypeParser(pg.types.builtins.INT8, Number);
+// One pool per isolate, created on first use so a missing SUPABASE_DB_URL is
+// reported as a request error rather than crashing the function at boot.
+let pool: pg.Pool | undefined;
+function getPool(): pg.Pool {
+ if (!pool) {
+ const connectionString = Deno.env.get("SUPABASE_DB_URL");
+ if (!connectionString) {
+ throw new Error("SUPABASE_DB_URL is not set");
+ }
+ pool = new pg.Pool({ connectionString, max: 4 });
+ }
+ return pool;
+}
+
// --- Database: get_schema ---
interface ColumnRow {
table_name: string;
column_name: string;
data_type: string;
+ udt_name: string;
is_nullable: string;
column_default: string | null;
table_type: string;
}
+// information_schema reports every extension or user type (citext, enums...)
+// as the SQL-standard placeholder "USER-DEFINED"; the actual name is udt_name.
+function columnType(row: ColumnRow): string {
+ return row.data_type === "USER-DEFINED" ? row.udt_name : row.data_type;
+}
+
interface ForeignKeyRow {
source_table: string;
source_column: string;
@@ -44,14 +102,16 @@ interface ForeignKeyRow {
target_column: string;
}
-async function getSchemaData(postgres: PostgresApi): Promise<string> {
+async function getSchemaData(postgres: RlsPostgres): Promise<string> {
// Runs as the caller's role, so information_schema only lists the
// columns the caller can actually read.
- const columns: ColumnRow[] = await postgres.query`
+ const columns = (await postgres.query(
+ `
SELECT
c.table_name,
c.column_name,
c.data_type,
+ c.udt_name,
c.is_nullable,
c.column_default,
t.table_type
@@ -60,9 +120,13 @@ async function getSchemaData(postgres: PostgresApi): Promise<string> {
ON c.table_name = t.table_name AND c.table_schema = t.table_schema
WHERE c.table_schema = 'public'
ORDER BY c.table_name, c.ordinal_position
- `;
+ `,
+ undefined,
+ { readOnly: true },
+ )) as ColumnRow[];
- const foreignKeyRows: ForeignKeyRow[] = await postgres.query`
+ const foreignKeyRows = (await postgres.query(
+ `
SELECT
src.relname AS source_table,
src_att.attname AS source_column,
@@ -78,7 +142,10 @@ async function getSchemaData(postgres: PostgresApi): Promise<string> {
ON tgt_att.attrelid = con.confrelid AND tgt_att.attnum = ANY(con.confkey)
WHERE con.contype = 'f' AND nsp.nspname = 'public'
ORDER BY src.relname
- `;
+ `,
+ undefined,
+ { readOnly: true },
+ )) as ForeignKeyRow[];
// Group columns by table
const tables = new Map<
@@ -102,7 +169,7 @@ async function getSchemaData(postgres: PostgresApi): Promise<string> {
}
tables.get(row.table_name)!.columns.push({
name: row.column_name,
- type: row.data_type,
+ type: columnType(row),
nullable: row.is_nullable === "YES",
default: row.column_default,
});
@@ -156,13 +223,14 @@ function errorMessage(error: unknown): string {
}
async function runValidatedSql(
- postgres: PostgresApi,
+ postgres: RlsPostgres,
sql: string,
validate: (sql: string) => string | null,
+ readOnly: boolean,
): Promise<
{ success: true; data: unknown[] } | { success: false; error: string }
> {
- // validate() also guarantees a single statement: queryRaw without params
+ // validate() also guarantees a single statement: a query without params
// uses the simple query protocol, which would otherwise accept a COMMIT
// that ends the RLS-scoped transaction.
const validationError = validate(sql);
@@ -170,7 +238,10 @@ async function runValidatedSql(
return { success: false, error: validationError };
}
try {
- return { success: true, data: await postgres.queryRaw(sql) };
+ return {
+ success: true,
+ data: await postgres.query(sql, undefined, { readOnly }),
+ };
} catch (error) {
return { success: false, error: errorMessage(error) };
}
@@ -198,7 +269,7 @@ function sqlToolResult(
// --- MCP Server Factory ---
-function createMcpServer(postgres: PostgresApi, userId: string): McpServer {
+function createMcpServer(postgres: RlsPostgres, userId: string): McpServer {
const server = new McpServer({
name: "atomic-crm",
version: "1.0.0",
@@ -239,7 +310,9 @@ Use the *_summary views (contacts_summary, companies_summary) for queries that n
To filter by the current user, if the table has a sales_id column, add a WHERE sales_id = auth.uid() clause to your query.
-This tool only supports SELECT queries. For INSERT, UPDATE, or DELETE operations, use the mutate tool.
+String comparisons are case-sensitive in this tool, including on citext columns (companies.website, sales.email): use ILIKE or lower() for case-insensitive matching.
+
+This tool only supports SELECT queries, executed in a read-only transaction. For INSERT, UPDATE, or DELETE operations, use the mutate tool.
Examples:
- "SELECT id, first_name, last_name, email_fts FROM contacts_summary WHERE email_fts LIKE '%@company.com%'"
@@ -255,7 +328,7 @@ Examples:
// eslint-disable-next-line no-console
console.log(`[MCP query] user=${userId} sql=${sql}`);
return sqlToolResult(
- await runValidatedSql(postgres, sql, validateReadOnly),
+ await runValidatedSql(postgres, sql, validateReadOnly, true),
);
},
);
@@ -277,6 +350,8 @@ Row Level Security (RLS) is enforced - mutations only affect data the authentica
IMPORTANT: Never specify sales_id in INSERT or UPDATE statements — it is automatically set to the authenticated user by a database trigger.
+String comparisons in WHERE clauses are case-sensitive in this tool, including on citext columns (companies.website, sales.email): use ILIKE or lower() for case-insensitive matching.
+
For read-only queries, use the query tool instead.
Examples:
@@ -293,7 +368,9 @@ Examples:
async ({ sql }) => {
// eslint-disable-next-line no-console
console.log(`[MCP mutate] user=${userId} sql=${sql}`);
- return sqlToolResult(await runValidatedSql(postgres, sql, validateWrite));
+ return sqlToolResult(
+ await runValidatedSql(postgres, sql, validateWrite, false),
+ );
},
);
@@ -418,9 +495,10 @@ Each task should include at least: id (required, used for the mark-as-done actio
try {
// RETURNING id distinguishes a successful update from an RLS-blocked
// or non-existent row (both affect 0 rows without an error).
- const rows = await postgres.query`
- UPDATE tasks SET done_date = NOW() WHERE id = ${id} RETURNING id
- `;
+ const rows = await postgres.query(
+ "UPDATE tasks SET done_date = NOW() WHERE id = $1 RETURNING id",
+ [id],
+ );
if (rows.length === 0) {
return {
content: [
@@ -455,8 +533,9 @@ Each task should include at least: id (required, used for the mark-as-done actio
// withOAuthProtectedResource serves the RFC 9728 metadata and adds the
// WWW-Authenticate challenge to 401s; withSupabase verifies the user's token
-// against the project JWKS; withPostgresClient runs every query in a
-// transaction scoped to the caller's claims and role, so RLS applies.
+// against the project JWKS; createRlsPostgres runs every query in a
+// transaction scoped to the caller's claims and role (so RLS applies), with a
+// pinned search_path, a statement timeout, and read-only mode for reads.
Deno.serve(
pipeline(
[
@@ -471,10 +550,18 @@ Deno.serve(
}),
withOAuthProtectedResource(),
withSupabase({ auth: "user" }),
- withPostgresClient(),
],
- (req, { postgres, jwtClaims }) => {
+ (req, { jwtClaims }) => {
const userId = String(jwtClaims?.sub);
+ let postgres: RlsPostgres;
+ try {
+ postgres = createRlsPostgres(getPool(), jwtClaims ?? {});
+ } catch (error) {
+ console.error(
+ `[MCP] cannot open database access: ${errorMessage(error)}`,
+ );
+ return new Response("Internal Server Error", { status: 500 });
+ }
// A fresh server per request: Edge Functions are stateless
const handler = createMcpHandler(() => createMcpServer(postgres, userId));
return handler.fetch(req);
diff --git a/supabase/functions/mcp/rlsPostgres.test.ts b/supabase/functions/mcp/rlsPostgres.test.ts
new file mode 100644
index 00000000..29a55e3a
--- /dev/null
+++ b/supabase/functions/mcp/rlsPostgres.test.ts
@@ -0,0 +1,187 @@
+// @vitest-environment node
+import { describe, it, expect } from "vitest";
+import {
+ createRlsPostgres,
+ SEARCH_PATH,
+ STATEMENT_TIMEOUT,
+ type SqlClient,
+ type SqlPool,
+} from "./rlsPostgres";
+
+interface RecordedQuery {
+ text: string;
+ params?: unknown[];
+}
+
+interface StubOptions {
+ // Thrown when the user statement (anything that is not part of the
+ // transaction prelude) runs.
+ failUserStatement?: Error;
+ failRollback?: boolean;
+}
+
+const PRELUDE = new Set([
+ "begin",
+ "commit",
+ "rollback",
+ "set transaction read only",
+]);
+
+function isPrelude(text: string): boolean {
+ return (
+ PRELUDE.has(text) ||
+ text.startsWith("select set_config('request.jwt.claims'") ||
+ text.startsWith("set local ")
+ );
+}
+
+function stubPool(options: StubOptions = {}) {
+ const queries: RecordedQuery[] = [];
+ const releases: (boolean | undefined)[] = [];
+ const client: SqlClient = {
+ query: async (text, params) => {
+ queries.push({ text, params });
+ if (text === "rollback" && options.failRollback) {
+ throw new Error("connection lost");
+ }
+ if (!isPrelude(text) && options.failUserStatement) {
+ throw options.failUserStatement;
+ }
+ return { rows: [{ ok: true }] };
+ },
+ release: (destroy) => {
+ releases.push(destroy);
+ },
+ };
+ const pool: SqlPool = { connect: async () => client };
+ return { pool, queries, releases };
+}
+
+const claims = { role: "authenticated", sub: "user-1" };
+
+describe("createRlsPostgres", () => {
+ it("wraps the statement in an RLS-scoped, search_path-pinned, time-limited transaction", async () => {
+ // Arrange
+ const { pool, queries, releases } = stubPool();
+ const postgres = createRlsPostgres(pool, claims);
+
+ // Act
+ const rows = await postgres.query("select * from contacts");
+
+ // Assert
+ expect(queries.map((q) => q.text)).toEqual([
+ "begin",
+ "select set_config('request.jwt.claims', $1, true)",
+ 'set local role "authenticated"',
+ `set local search_path = ${SEARCH_PATH}`,
+ `set local statement_timeout = '${STATEMENT_TIMEOUT}'`,
+ "select * from contacts",
+ "commit",
+ ]);
+ expect(queries[1].params).toEqual([JSON.stringify(claims)]);
+ expect(rows).toEqual([{ ok: true }]);
+ expect(releases).toEqual([false]);
+ });
+
+ it("pins the search_path to public only", () => {
+ expect(SEARCH_PATH).toBe("public");
+ });
+
+ it("makes the transaction read only when asked", async () => {
+ // Arrange
+ const { pool, queries } = stubPool();
+ const postgres = createRlsPostgres(pool, claims);
+
+ // Act
+ await postgres.query("select 1", undefined, { readOnly: true });
+
+ // Assert
+ const texts = queries.map((q) => q.text);
+ expect(texts.indexOf("set transaction read only")).toBeGreaterThan(
+ texts.indexOf('set local role "authenticated"'),
+ );
+ expect(texts.indexOf("set transaction read only")).toBeLessThan(
+ texts.indexOf("select 1"),
+ );
+ });
+
+ it("passes bind parameters through to the statement", async () => {
+ // Arrange
+ const { pool, queries } = stubPool();
+ const postgres = createRlsPostgres(pool, claims);
+
+ // Act
+ await postgres.query(
+ "update tasks set done_date = now() where id = $1",
+ [42],
+ );
+
+ // Assert
+ expect(queries.at(-2)).toEqual({
+ text: "update tasks set done_date = now() where id = $1",
+ params: [42],
+ });
+ });
+
+ it("rolls back, releases the connection and rethrows when the statement fails", async () => {
+ // Arrange
+ const failure = new Error("boom");
+ const { pool, queries, releases } = stubPool({
+ failUserStatement: failure,
+ });
+ const postgres = createRlsPostgres(pool, claims);
+
+ // Act
+ const run = postgres.query("select bad");
+
+ // Assert
+ await expect(run).rejects.toBe(failure);
+ expect(queries.map((q) => q.text)).toContain("rollback");
+ expect(queries.map((q) => q.text)).not.toContain("commit");
+ expect(releases).toEqual([false]);
+ });
+
+ it("destroys the connection when the rollback itself fails", async () => {
+ // Arrange
+ const { pool, releases } = stubPool({
+ failUserStatement: new Error("boom"),
+ failRollback: true,
+ });
+ const postgres = createRlsPostgres(pool, claims);
+
+ // Act
+ await expect(postgres.query("select bad")).rejects.toThrow("boom");
+
+ // Assert
+ expect(releases).toEqual([true]);
+ });
+
+ it("explains permission denied errors in terms of the caller's role", async () => {
+ // Arrange
+ const denied = Object.assign(new Error("permission denied for table x"), {
+ code: "42501",
+ });
+ const { pool } = stubPool({ failUserStatement: denied });
+ const postgres = createRlsPostgres(pool, claims);
+
+ // Act & Assert
+ await expect(postgres.query("select * from x")).rejects.toThrow(
+ /grant select on <table> to authenticated/,
+ );
+ });
+
+ it.each([
+ ["service_role", { role: "service_role", sub: "user-1" }],
+ ["anon", { role: "anon" }],
+ ["a missing role", { sub: "user-1" }],
+ ])("refuses %s before touching the database", (_label, badClaims) => {
+ // Arrange
+ const { pool, queries } = stubPool();
+
+ // Act & Assert
+ expect(() => createRlsPostgres(pool, badClaims)).toThrow(
+ /Unsupported role/,
+ );
+ expect(queries).toHaveLength(0);
+ });
+});
diff --git a/supabase/functions/mcp/rlsPostgres.ts b/supabase/functions/mcp/rlsPostgres.ts
new file mode 100644
index 00000000..048bcbb2
--- /dev/null
+++ b/supabase/functions/mcp/rlsPostgres.ts
@@ -0,0 +1,129 @@
+// RLS-scoped SQL execution for the MCP tools.
+//
+// Replaces @supabase/server's withPostgresClient, which runs every query as
+// `begin; set_config(claims); set local role; <sql>; commit` and offers no way
+// to extend that prelude. The connection string is Supabase's SUPABASE_DB_URL,
+// i.e. the `postgres` role (BYPASSRLS, member of service_role), so everything
+// that keeps a query inside the caller's rights happens in this transaction.
+//
+// This module has no npm: imports on purpose: it only needs the `query` and
+// `release` shape of a pg client, so the unit tests drive it with a stub.
+
+export interface SqlQueryResult {
+ rows: unknown[];
+}
+
+export interface SqlClient {
+ query(text: string, params?: unknown[]): Promise<SqlQueryResult>;
+ release(destroy?: boolean): void;
+}
+
+export interface SqlPool {
+ connect(): Promise<SqlClient>;
+}
+
+export interface QueryOptions {
+ // Runs the statement in a READ ONLY transaction: Postgres then refuses any
+ // write, including those hidden inside a volatile function called from a
+ // SELECT (merge_contacts, pg_net's request queue...).
+ readOnly?: boolean;
+}
+
+export interface RlsPostgres {
+ query(
+ text: string,
+ params?: unknown[],
+ options?: QueryOptions,
+ ): Promise<unknown[]>;
+}
+
+// Only role the MCP endpoint ever assumes. withSupabase({ auth: "user" })
+// already guarantees a user token; refusing anything else here means a
+// surprising claim can never widen the role instead of silently narrowing it.
+const ALLOWED_ROLE = "authenticated";
+
+// Same budget as the `authenticated` role gets through PostgREST. That role
+// setting does not apply here: statement_timeout from a role's config is read
+// at login, and this connection logs in as `postgres`, not as `authenticated`.
+export const STATEMENT_TIMEOUT = "8s";
+
+// Only `public` (pg_catalog stays implicit). `extensions` and `net` hold the
+// http functions that let a query make the database issue HTTP requests;
+// keeping them off the search_path means an unqualified `http_get(...)` does
+// not resolve, whatever the SQL validator did or did not catch. Functions in
+// `public` carry their own `SET search_path`, so they are unaffected.
+export const SEARCH_PATH = "public";
+
+const PERMISSION_DENIED = "42501";
+
+function resolveRole(claims: Record<string, unknown>): string {
+ const requested = claims.role;
+ if (requested !== ALLOWED_ROLE) {
+ throw new Error(
+ `Unsupported role ${JSON.stringify(requested)}: the MCP server only runs queries as "${ALLOWED_ROLE}".`,
+ );
+ }
+ return requested;
+}
+
+async function runInTransaction(
+ client: SqlClient,
+ claims: Record<string, unknown>,
+ role: string,
+ text: string,
+ params: unknown[] | undefined,
+ options: QueryOptions,
+): Promise<unknown[]> {
+ await client.query("begin");
+ await client.query(`select set_config('request.jwt.claims', $1, true)`, [
+ JSON.stringify(claims),
+ ]);
+ await client.query(`set local role "${role}"`);
+ await client.query(`set local search_path = ${SEARCH_PATH}`);
+ await client.query(`set local statement_timeout = '${STATEMENT_TIMEOUT}'`);
+ if (options.readOnly) {
+ await client.query("set transaction read only");
+ }
+ const result = await client.query(text, params);
+ await client.query("commit");
+ return result.rows;
+}
+
+export function createRlsPostgres(
+ pool: SqlPool,
+ claims: Record<string, unknown>,
+): RlsPostgres {
+ const role = resolveRole(claims);
+ return {
+ async query(text, params, options = {}) {
+ const client = await pool.connect();
+ let poisoned = false;
+ try {
+ return await runInTransaction(
+ client,
+ claims,
+ role,
+ text,
+ params,
+ options,
+ );
+ } catch (error) {
+ try {
+ await client.query("rollback");
+ } catch {
+ // The connection is in an unknown state: drop it from the pool.
+ poisoned = true;
+ }
+ if (
+ error instanceof Error &&
+ (error as { code?: string }).code === PERMISSION_DENIED
+ ) {
+ error.message += ` (queries run as the caller's role '${role}'; grant that role the table privileges it needs, e.g. "grant select on <table> to ${role}")`;
+ }
+ throw error;
+ } finally {
+ client.release(poisoned);
+ }
+ },
+ };
+}
diff --git a/supabase/functions/mcp/validateSql.test.ts b/supabase/functions/mcp/validateSql.test.ts
index 8b3f9829..984e1caf 100644
--- a/supabase/functions/mcp/validateSql.test.ts
+++ b/supabase/functions/mcp/validateSql.test.ts
@@ -25,6 +25,11 @@ describe("validateReadOnly", () => {
"aggregate query",
"SELECT COUNT(*) as total, type FROM tasks GROUP BY type",
],
+ [
+ "window function",
+ "SELECT id, row_number() OVER (PARTITION BY company_id ORDER BY created_at) FROM contacts",
+ ],
+ ["DISTINCT ON a column", "SELECT DISTINCT ON (company_id) * FROM contacts"],
[
"DELETE in string literal",
"SELECT * FROM contacts WHERE status = 'DELETE'",
@@ -42,6 +47,15 @@ describe("validateReadOnly", () => {
"SELECT /* DROP TABLE contacts */ * FROM contacts",
],
["DROP in line comment", "SELECT * FROM contacts -- DROP TABLE contacts"],
+ ["auth schema function", "SELECT * FROM tasks WHERE sales_id = auth.uid()"],
+ ["pg_catalog schema function", "SELECT pg_catalog.now()"],
+ ["public schema function", "SELECT public.search_query('john')"],
+ [
+ // Not the validator's job: the transaction wrapper sets search_path to
+ // `public`, so this name does not resolve and Postgres rejects it.
+ "unqualified http extension function",
+ "SELECT * FROM http_get('http://127.0.0.1/')",
+ ],
])("allows %s", (_label, sql) => {
expect(validateReadOnly(sql)).toBeNull();
});
@@ -88,9 +102,48 @@ describe("validateReadOnly", () => {
"set_config in a subquery",
"SELECT id FROM contacts WHERE first_name = (SELECT set_config('role', 'postgres', true))",
],
+ [
+ "set_config in DISTINCT ON (role escalation)",
+ "SELECT DISTINCT ON (set_config('role', 'service_role', false)) 1",
+ ],
+ [
+ "set_config in DISTINCT ON (claims impersonation)",
+ "SELECT DISTINCT ON (set_config('request.jwt.claims', '{\"sub\":\"other\"}', true)) 1",
+ ],
+ [
+ "set_config in OVER (PARTITION BY)",
+ "SELECT count(*) OVER (PARTITION BY set_config('role', 'service_role', true)) FROM contacts",
+ ],
+ [
+ "set_config in OVER (ORDER BY)",
+ "SELECT count(*) OVER (ORDER BY set_config('role', 'service_role', true)) FROM contacts",
+ ],
+ [
+ "http extension as a table function (SSRF)",
+ "SELECT * FROM extensions.http_get('http://169.254.169.254/latest/meta-data/')",
+ ],
+ [
+ "http extension in an expression (SSRF)",
+ "SELECT extensions.http_get('http://127.0.0.1:54321/')",
+ ],
+ [
+ "http extension POST (SSRF)",
+ "SELECT content FROM extensions.http_post('http://127.0.0.1/', 'a', 'text/plain')",
+ ],
+ ["pg_net function (SSRF)", "SELECT net.http_get('http://127.0.0.1/')"],
+ [
+ "uppercase schema qualification",
+ "SELECT * FROM EXTENSIONS.HTTP_GET('http://127.0.0.1/')",
+ ],
])("rejects %s", (_label, sql) => {
expect(validateReadOnly(sql)).not.toBeNull();
});
+
+ it("names the offending schema-qualified function", () => {
+ expect(
+ validateReadOnly("SELECT * FROM extensions.http_get('http://x/')"),
+ ).toMatch(/"extensions\.http_get" is not allowed/);
+ });
});
describe("validateWrite", () => {
@@ -113,6 +166,10 @@ describe("validateWrite", () => {
"writable CTE with INSERT",
"WITH d AS (DELETE FROM old_contacts RETURNING *) INSERT INTO archive SELECT * FROM d",
],
+ [
+ "UPDATE scoped to the caller",
+ "UPDATE tasks SET done_date = now() WHERE id = 1 AND sales_id = auth.uid()",
+ ],
])("allows %s", (_label, sql) => {
expect(validateWrite(sql)).toBeNull();
});
@@ -140,6 +197,18 @@ describe("validateWrite", () => {
"set_config in an UPDATE",
"UPDATE tasks SET text = set_config('role', 'postgres', true) WHERE id = 1",
],
+ [
+ "set_config in the DISTINCT ON of an INSERT ... SELECT",
+ "INSERT INTO contacts (first_name) SELECT DISTINCT ON (set_config('role', 'service_role', true)) 'x'",
+ ],
+ [
+ "http extension in an UPDATE (SSRF)",
+ "UPDATE tasks SET text = (SELECT content FROM extensions.http_get('http://127.0.0.1/')) WHERE id = 1",
+ ],
+ [
+ "pg_net in an INSERT ... SELECT (SSRF)",
+ "INSERT INTO tasks (text) SELECT net.http_get('http://127.0.0.1/')::text",
+ ],
])("rejects %s", (_label, sql) => {
expect(validateWrite(sql)).not.toBeNull();
});
diff --git a/supabase/functions/mcp/validateSql.ts b/supabase/functions/mcp/validateSql.ts
index b5c5491d..ae6816ec 100644
--- a/supabase/functions/mcp/validateSql.ts
+++ b/supabase/functions/mcp/validateSql.ts
@@ -1,4 +1,4 @@
-import { astVisitor, parse, type Statement } from "npm:pgsql-ast-parser@^12";
+import { parse, type Statement } from "npm:pgsql-ast-parser@^12";
const ALLOWED_READ_TYPES = new Set(["select", "with"]);
const ALLOWED_WRITE_TYPES = new Set(["insert", "update", "delete", "with"]);
@@ -8,18 +8,65 @@ const ALLOWED_WRITE_TYPES = new Set(["insert", "update", "delete", "with"]);
// either mid-statement and act as another user, so it is never allowed.
const FORBIDDEN_FUNCTIONS = new Set(["set_config"]);
+// Schema-qualified calls may only target these schemas. `extensions` (http
+// extension) and `net` (pg_net) hold functions that make the database issue
+// HTTP requests, which turns the query tool into an SSRF primitive; their
+// EXECUTE grants cannot be revoked from a migration (they are owned by
+// supabase_admin), so the endpoint has to refuse them itself. Unqualified
+// names are left to Postgres: the transaction wrapper sets search_path to
+// `public` (pg_catalog is implicit), so an unqualified `http_get(...)` does not
+// resolve at all. The two layers back each other up.
+const ALLOWED_FUNCTION_SCHEMAS = new Set(["public", "pg_catalog", "auth"]);
+
+interface FunctionCall {
+ schema?: string;
+ name: string;
+}
+
+function isFunctionCallNode(
+ node: unknown,
+): node is { type: "call"; function: FunctionCall } {
+ if (typeof node !== "object" || node === null) return false;
+ const candidate = node as { type?: unknown; function?: unknown };
+ return (
+ candidate.type === "call" &&
+ typeof candidate.function === "object" &&
+ candidate.function !== null &&
+ typeof (candidate.function as FunctionCall).name === "string"
+ );
+}
+
+// Walk the raw AST rather than pgsql-ast-parser's astVisitor: the visitor only
+// reaches the fields its default mapper enumerates, and it skips the
+// expression lists of `DISTINCT ON (...)` and `OVER (...)`, which was enough
+// to smuggle a set_config() call past the previous version of this check.
+// Descending into every object and array reaches a call wherever it sits.
+function collectFunctionCalls(node: unknown, calls: FunctionCall[]): void {
+ if (Array.isArray(node)) {
+ for (const child of node) collectFunctionCalls(child, calls);
+ return;
+ }
+ if (typeof node !== "object" || node === null) return;
+ if (isFunctionCallNode(node)) {
+ calls.push(node.function);
+ }
+ for (const child of Object.values(node)) collectFunctionCalls(child, calls);
+}
+
function findForbiddenCall(stmts: Statement[]): string | null {
- let found: string | null = null;
- const visitor = astVisitor((map) => ({
- call: (call) => {
- if (FORBIDDEN_FUNCTIONS.has(call.function.name.toLowerCase())) {
- found = call.function.name;
- }
- map.super().call(call);
- },
- }));
- for (const stmt of stmts) visitor.statement(stmt);
- return found;
+ const calls: FunctionCall[] = [];
+ collectFunctionCalls(stmts, calls);
+ for (const call of calls) {
+ const name = call.name.toLowerCase();
+ if (FORBIDDEN_FUNCTIONS.has(name)) {
+ return `Function "${call.name}" is not allowed.`;
+ }
+ const schema = call.schema?.toLowerCase();
+ if (schema !== undefined && !ALLOWED_FUNCTION_SCHEMAS.has(schema)) {
+ return `Function "${call.schema}.${call.name}" is not allowed: only functions from the ${[...ALLOWED_FUNCTION_SCHEMAS].join(", ")} schemas can be called.`;
+ }
+ }
+ return null;
}
// Collect all statement types found in a parsed AST, including inner
@@ -39,7 +86,9 @@ function collectStatementTypes(stmts: Statement[]): Set<string> {
return types;
}
-export function validateReadOnly(sql: string): string | null {
+function parseSingleStatement(
+ sql: string,
+): { stmts: Statement[] } | { error: string } {
let stmts: Statement[];
try {
stmts = parse(sql);
@@ -48,53 +97,35 @@ export function validateReadOnly(sql: string): string | null {
// pgsql-ast-parser appends a parse-table dump that is useless to the
// LLM and consumes many tokens; keep the diagnostic prefix only.
const message = raw.split("Here is the state of my parse table")[0].trim();
- return `Failed to parse SQL: ${message}`;
+ return { error: `Failed to parse SQL: ${message}` };
}
if (stmts.length === 0) {
- return "Empty query.";
+ return { error: "Empty query." };
}
if (stmts.length > 1) {
- return "Only a single statement is allowed.";
+ return { error: "Only a single statement is allowed." };
}
- const types = collectStatementTypes(stmts);
- for (const type of types) {
+ return { stmts };
+}
+
+export function validateReadOnly(sql: string): string | null {
+ const parsed = parseSingleStatement(sql);
+ if ("error" in parsed) return parsed.error;
+ for (const type of collectStatementTypes(parsed.stmts)) {
if (!ALLOWED_READ_TYPES.has(type)) {
return `Statement type "${type}" is not allowed in read-only queries. Use the mutate tool for data modifications.`;
}
}
- const forbiddenCall = findForbiddenCall(stmts);
- if (forbiddenCall) {
- return `Function "${forbiddenCall}" is not allowed.`;
- }
- return null;
+ return findForbiddenCall(parsed.stmts);
}
export function validateWrite(sql: string): string | null {
- let stmts: Statement[];
- try {
- stmts = parse(sql);
- } catch (err) {
- const raw = err instanceof Error ? err.message : String(err);
- // pgsql-ast-parser appends a parse-table dump that is useless to the
- // LLM and consumes many tokens; keep the diagnostic prefix only.
- const message = raw.split("Here is the state of my parse table")[0].trim();
- return `Failed to parse SQL: ${message}`;
- }
- if (stmts.length === 0) {
- return "Empty query.";
- }
- if (stmts.length > 1) {
- return "Only a single statement is allowed.";
- }
- const types = collectStatementTypes(stmts);
- for (const type of types) {
+ const parsed = parseSingleStatement(sql);
+ if ("error" in parsed) return parsed.error;
+ for (const type of collectStatementTypes(parsed.stmts)) {
if (!ALLOWED_WRITE_TYPES.has(type)) {
return `Statement type "${type}" is not allowed. Only INSERT, UPDATE, and DELETE statements are supported.`;
}
}
- const forbiddenCall = findForbiddenCall(stmts);
- if (forbiddenCall) {
- return `Function "${forbiddenCall}" is not allowed.`;
- }
- return null;
+ return findForbiddenCall(parsed.stmts);
}