Skip to content

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

Reset session state and block XML export functions in the MCP server

François Zaninotto28b8963d1597
diff --git a/supabase/functions/mcp/index.ts b/supabase/functions/mcp/index.ts
index 95d82102..1f40ab0c 100644
--- a/supabase/functions/mcp/index.ts
+++ b/supabase/functions/mcp/index.ts
@@ -16,10 +16,12 @@
//
// 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 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).
+// could rewrite the claims or the role mid-statement), none of the
+// pg_catalog `*_to_xml` functions (they execute SQL or resolve object names
+// passed as strings, which the AST cannot see), 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
@@ -34,6 +36,9 @@
// - `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.
+// - `DISCARD ALL` after every transaction: session state that outlives a
+// COMMIT (session-level advisory locks, LISTEN, temp objects) is dropped
+// before the pooled connection serves the next request.
//
// Consequence worth knowing: with `extensions` off the search_path, the
// `citext` operators are not visible either, so `=` on citext columns
diff --git a/supabase/functions/mcp/rlsPostgres.test.ts b/supabase/functions/mcp/rlsPostgres.test.ts
index 29a55e3a..b6dd850f 100644
--- a/supabase/functions/mcp/rlsPostgres.test.ts
+++ b/supabase/functions/mcp/rlsPostgres.test.ts
@@ -18,12 +18,14 @@ interface StubOptions {
// transaction prelude) runs.
failUserStatement?: Error;
failRollback?: boolean;
+ failDiscard?: boolean;
}
const PRELUDE = new Set([
"begin",
"commit",
"rollback",
+ "discard all",
"set transaction read only",
]);
@@ -44,6 +46,9 @@ function stubPool(options: StubOptions = {}) {
if (text === "rollback" && options.failRollback) {
throw new Error("connection lost");
}
+ if (text === "discard all" && options.failDiscard) {
+ throw new Error("connection lost");
+ }
if (!isPrelude(text) && options.failUserStatement) {
throw options.failUserStatement;
}
@@ -77,6 +82,7 @@ describe("createRlsPostgres", () => {
`set local statement_timeout = '${STATEMENT_TIMEOUT}'`,
"select * from contacts",
"commit",
+ "discard all",
]);
expect(queries[1].params).toEqual([JSON.stringify(claims)]);
expect(rows).toEqual([{ ok: true }]);
@@ -117,7 +123,7 @@ describe("createRlsPostgres", () => {
);
// Assert
- expect(queries.at(-2)).toEqual({
+ expect(queries.at(-3)).toEqual({
text: "update tasks set done_date = now() where id = $1",
params: [42],
});
@@ -136,11 +142,42 @@ describe("createRlsPostgres", () => {
// Assert
await expect(run).rejects.toBe(failure);
- expect(queries.map((q) => q.text)).toContain("rollback");
- expect(queries.map((q) => q.text)).not.toContain("commit");
+ const texts = queries.map((q) => q.text);
+ expect(texts).toContain("rollback");
+ expect(texts).not.toContain("commit");
+ expect(texts.at(-1)).toBe("discard all");
expect(releases).toEqual([false]);
});
+ it("does not try to clean a connection whose rollback failed", async () => {
+ // Arrange
+ const { pool, queries, 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(queries.map((q) => q.text)).not.toContain("discard all");
+ expect(releases).toEqual([true]);
+ });
+
+ it("destroys the connection when the session cleanup fails", async () => {
+ // Arrange
+ const { pool, releases } = stubPool({ failDiscard: true });
+ const postgres = createRlsPostgres(pool, claims);
+
+ // Act
+ const rows = await postgres.query("select 1");
+
+ // Assert
+ expect(rows).toEqual([{ ok: true }]);
+ expect(releases).toEqual([true]);
+ });
+
it("destroys the connection when the rollback itself fails", async () => {
// Arrange
const { pool, releases } = stubPool({
diff --git a/supabase/functions/mcp/rlsPostgres.ts b/supabase/functions/mcp/rlsPostgres.ts
index 048bcbb2..f5d8abc1 100644
--- a/supabase/functions/mcp/rlsPostgres.ts
+++ b/supabase/functions/mcp/rlsPostgres.ts
@@ -122,6 +122,17 @@ export function createRlsPostgres(
}
throw error;
} finally {
+ if (!poisoned) {
+ // The pool is shared by every caller and logs in as `postgres`:
+ // drop whatever session state the statement may have left behind
+ // (session-level advisory locks, LISTEN, temp objects...) so nothing
+ // carries over to the next request.
+ try {
+ await client.query("discard all");
+ } catch {
+ poisoned = true;
+ }
+ }
client.release(poisoned);
}
},
diff --git a/supabase/functions/mcp/validateSql.test.ts b/supabase/functions/mcp/validateSql.test.ts
index a0f17fa8..05294fff 100644
--- a/supabase/functions/mcp/validateSql.test.ts
+++ b/supabase/functions/mcp/validateSql.test.ts
@@ -158,6 +158,22 @@ describe("validateReadOnly", () => {
"SELECT (SELECT content FROM net._http_response LIMIT 1)",
],
["extension-schema type in a cast", "SELECT 'x'::extensions.citext"],
+ [
+ "query_to_xml executing SQL from a string (SSRF)",
+ "SELECT query_to_xml('select net.http_get(''http://127.0.0.1/'')', false, true, '')",
+ ],
+ [
+ "table_to_xml reading a blocked schema by name",
+ "SELECT table_to_xml('net._http_response'::regclass, true, false, '')",
+ ],
+ [
+ "schema_to_xml dumping a blocked schema",
+ "SELECT schema_to_xml('net', true, false, '')",
+ ],
+ [
+ "quoted, schema-qualified query_to_xmlschema",
+ "SELECT pg_catalog.\"QUERY_TO_XMLSCHEMA\"('select 1', false, true, '')",
+ ],
])("rejects %s", (_label, sql) => {
expect(validateReadOnly(sql)).not.toBeNull();
});
@@ -252,6 +268,10 @@ describe("validateWrite", () => {
"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"],
+ [
+ "query_to_xml enqueueing a pg_net request from an INSERT (SSRF)",
+ "INSERT INTO tasks (text) SELECT query_to_xml('select net.http_get(''http://127.0.0.1/'')', false, true, '')::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 2df20e0b..32b59933 100644
--- a/supabase/functions/mcp/validateSql.ts
+++ b/supabase/functions/mcp/validateSql.ts
@@ -6,7 +6,30 @@ const ALLOWED_WRITE_TYPES = new Set(["insert", "update", "delete", "with"]);
// RLS reads the caller's identity from the request.jwt.claims setting, and the
// role from the role setting. A query able to call set_config() could rewrite
// either mid-statement and act as another user, so it is never allowed.
-const FORBIDDEN_FUNCTIONS = new Set(["set_config"]);
+//
+// The *_to_xml family takes a query or an object name as a TEXT argument and
+// executes it: the SQL inside the string is invisible to the AST walk below
+// and resolves names against the real catalog, so it would reach the `net`
+// and `extensions` objects the schema allowlist refuses. These functions live
+// in pg_catalog with a PUBLIC grant that migrations cannot revoke (owned by
+// supabase_admin), so they are refused here by name. The CRM never uses them.
+const FORBIDDEN_FUNCTIONS = new Set([
+ "set_config",
+ "query_to_xml",
+ "query_to_xmlschema",
+ "query_to_xml_and_xmlschema",
+ "table_to_xml",
+ "table_to_xmlschema",
+ "table_to_xml_and_xmlschema",
+ "cursor_to_xml",
+ "cursor_to_xmlschema",
+ "database_to_xml",
+ "database_to_xmlschema",
+ "database_to_xml_and_xmlschema",
+ "schema_to_xml",
+ "schema_to_xmlschema",
+ "schema_to_xml_and_xmlschema",
+]);
// Schema-qualified references (tables, functions, types...) may only target
// these schemas. `extensions` (http extension) and `net` (pg_net) hold the