A full-featured CRM built with React, shadcn/ui, and Supabase.
Extend the MCP SQL validator to table references
François Zaninotto9e2bd2de1758
diff --git a/supabase/functions/mcp/index.ts b/supabase/functions/mcp/index.tsindex 35bf6af0..95d82102 100644--- a/supabase/functions/mcp/index.ts+++ b/supabase/functions/mcp/index.ts@@ -16,18 +16,19 @@//// 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).+// could rewrite the claims or the role mid-statement), and every+// schema-qualified reference (table, function, type) restricted to+// `public`, `pg_catalog`, `auth` and `information_schema`. 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.+// `pg_net` (net schema) functions, and pg_net's request queue and+// response tables, let a query make the database issue HTTP requests,+// i.e. an SSRF primitive. Their 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(...)` or+// `http_request_queue` 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`,diff --git a/supabase/functions/mcp/validateSql.test.ts b/supabase/functions/mcp/validateSql.test.tsindex 984e1caf..a0f17fa8 100644--- a/supabase/functions/mcp/validateSql.test.ts+++ b/supabase/functions/mcp/validateSql.test.ts@@ -50,6 +50,12 @@ describe("validateReadOnly", () => {["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')"],+ ["public schema table", "SELECT id FROM public.contacts"],+ ["pg_catalog table", "SELECT relname FROM pg_catalog.pg_class"],+ [+ "information_schema view",+ "SELECT table_name FROM information_schema.tables",+ ],[// Not the validator's job: the transaction wrapper sets search_path to// `public`, so this name does not resolve and Postgres rejects it.@@ -135,14 +141,34 @@ describe("validateReadOnly", () => {"uppercase schema qualification","SELECT * FROM EXTENSIONS.HTTP_GET('http://127.0.0.1/')",],+ [+ "pg_net response table (SSRF read-back)",+ "SELECT status_code, content FROM net._http_response",+ ],+ [+ "pg_net table in a JOIN",+ "SELECT c.id FROM contacts c JOIN net._http_response r ON r.id = c.id",+ ],+ [+ "pg_net table in a CTE",+ "WITH r AS (SELECT content FROM net._http_response) SELECT * FROM r",+ ],+ [+ "pg_net table in a subquery",+ "SELECT (SELECT content FROM net._http_response LIMIT 1)",+ ],+ ["extension-schema type in a cast", "SELECT 'x'::extensions.citext"],])("rejects %s", (_label, sql) => {expect(validateReadOnly(sql)).not.toBeNull();});- it("names the offending schema-qualified function", () => {+ it("names the offending schema-qualified reference", () => {expect(validateReadOnly("SELECT * FROM extensions.http_get('http://x/')"),).toMatch(/"extensions\.http_get" is not allowed/);+ expect(validateReadOnly("SELECT * FROM net._http_response")).toMatch(+ /"net\._http_response" is not allowed/,+ );});});@@ -170,6 +196,10 @@ describe("validateWrite", () => {"UPDATE scoped to the caller","UPDATE tasks SET done_date = now() WHERE id = 1 AND sales_id = auth.uid()",],+ [+ "INSERT into a public-qualified table",+ "INSERT INTO public.tasks (text) VALUES ('x')",+ ],])("allows %s", (_label, sql) => {expect(validateWrite(sql)).toBeNull();});@@ -209,6 +239,19 @@ describe("validateWrite", () => {"pg_net in an INSERT ... SELECT (SSRF)","INSERT INTO tasks (text) SELECT net.http_get('http://127.0.0.1/')::text",],+ [+ "direct INSERT into the pg_net request queue (SSRF)",+ "INSERT INTO net.http_request_queue (method, url, headers, timeout_milliseconds) VALUES ('GET', 'http://169.254.169.254/latest/meta-data/', '{}', 5000)",+ ],+ [+ "writable CTE into the pg_net request queue (SSRF)",+ "WITH q AS (INSERT INTO net.http_request_queue (method, url, headers, timeout_milliseconds) VALUES ('GET', 'http://127.0.0.1/', '{}', 5000) RETURNING id) INSERT INTO tasks (text) SELECT id::text FROM q",+ ],+ [+ "UPDATE on a pg_net table",+ "UPDATE net.http_request_queue SET url = 'http://127.0.0.1/' WHERE id = 1",+ ],+ ["DELETE on a pg_net table", "DELETE FROM net._http_response WHERE id = 1"],])("rejects %s", (_label, sql) => {expect(validateWrite(sql)).not.toBeNull();});diff --git a/supabase/functions/mcp/validateSql.ts b/supabase/functions/mcp/validateSql.tsindex ae6816ec..2df20e0b 100644--- a/supabase/functions/mcp/validateSql.ts+++ b/supabase/functions/mcp/validateSql.ts@@ -8,31 +8,45 @@ 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"]);+// Schema-qualified references (tables, functions, types...) may only target+// these schemas. `extensions` (http extension) and `net` (pg_net) hold the+// functions AND the queue tables that make the database issue HTTP requests,+// which turns the SQL tools into an SSRF primitive; their 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(...)` or `http_request_queue` does not resolve at+// all. The two layers back each other up.+const ALLOWED_SCHEMAS = new Set([+ "public",+ "pg_catalog",+ "auth",+ "information_schema",+]);-interface FunctionCall {+interface QualifiedName {schema?: string;name: string;}+// pgsql-ast-parser gives every named reference (table, function, type, column+// qualifier) the same { schema?, name } shape, so one predicate covers them.+function isQualifiedName(node: object): node is QualifiedName {+ const candidate = node as { schema?: unknown; name?: unknown };+ return (+ typeof candidate.schema === "string" && typeof candidate.name === "string"+ );+}+function isFunctionCallNode(- node: unknown,-): node is { type: "call"; function: FunctionCall } {- if (typeof node !== "object" || node === null) return false;+ node: object,+): node is { type: "call"; function: { name: string } } {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"+ typeof (candidate.function as { name?: unknown }).name === "string");}@@ -40,31 +54,31 @@ function isFunctionCallNode(// 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 {+// Descending into every object and array reaches a node wherever it sits.+function findForbiddenReference(node: unknown): string | null {if (Array.isArray(node)) {- for (const child of node) collectFunctionCalls(child, calls);- return;+ for (const child of node) {+ const found = findForbiddenReference(child);+ if (found) return found;+ }+ return null;}- if (typeof node !== "object" || node === null) return;- if (isFunctionCallNode(node)) {- calls.push(node.function);+ if (typeof node !== "object" || node === null) return null;+ if (+ isFunctionCallNode(node) &&+ FORBIDDEN_FUNCTIONS.has(node.function.name.toLowerCase())+ ) {+ return `Function "${node.function.name}" is not allowed.`;}- for (const child of Object.values(node)) collectFunctionCalls(child, calls);-}--function findForbiddenCall(stmts: Statement[]): string | null {- 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.`;- }+ if (+ isQualifiedName(node) &&+ !ALLOWED_SCHEMAS.has(node.schema.toLowerCase())+ ) {+ return `Reference to "${node.schema}.${node.name}" is not allowed: only objects from the ${[...ALLOWED_SCHEMAS].join(", ")} schemas can be used.`;+ }+ for (const child of Object.values(node)) {+ const found = findForbiddenReference(child);+ if (found) return found;}return null;}@@ -116,7 +130,7 @@ export function validateReadOnly(sql: string): string | null {return `Statement type "${type}" is not allowed in read-only queries. Use the mutate tool for data modifications.`;}}- return findForbiddenCall(parsed.stmts);+ return findForbiddenReference(parsed.stmts);}export function validateWrite(sql: string): string | null {@@ -127,5 +141,5 @@ export function validateWrite(sql: string): string | null {return `Statement type "${type}" is not allowed. Only INSERT, UPDATE, and DELETE statements are supported.`;}}- return findForbiddenCall(parsed.stmts);+ return findForbiddenReference(parsed.stmts);}