--- name: safe-sql-execution description: >- Provenance-tracked SQL execution rules for Postgres (SafeSqlFragment via pg-meta) and Analytics/Logs (SafeLogSqlFragment via safe-analytics-sql). Load BEFORE writing or editing any SQL query builder, pg-meta helper, tables/views/ functions/triggers/indexes/RLS policy SQL, interpolated schema/table/column/ search/route params, round-tripped DB/snippet SQL, or Run/Apply/Execute SQL action (executeSql / executeAnalyticsSql) — even when the task never mentions security or SafeSqlFragment. --- # Safe SQL Execution Studio runs SQL directly against the authenticated user's Postgres database and analytics logs. Our security model is **proven authorship**: users may run any SQL they explicitly authored or that is hardcoded in the app, but SQL influenced by external input (URL params, LLM output, auto-saved snippets) must never execute without sanitization or an explicit user run gesture. Two intentionally **disjoint** branded type systems enforce this at compile time: - **Postgres SQL**: `SafeSqlFragment` from `@supabase/pg-meta` → `executeSql` (`apps/studio/data/sql/execute-sql-mutation.ts`) - **Analytics / Logs SQL**: `SafeLogSqlFragment` from `apps/studio/data/logs/safe-analytics-sql.ts` → `executeAnalyticsSql` (`apps/studio/data/logs/execute-analytics-sql.ts`) --- ## Postgres SQL (`@supabase/pg-meta`) ### Branded types & provenance rules - `SafeSqlFragment`: safe to execute (hardcoded via `safeSql`, sanitized via `ident`/`literal`/`keyword`, or user-authored via `SafeSqlInput` / `acceptUntrustedSql`). `executeSql` rejects plain `string` and `UntrustedSqlFragment` at compile time. - `WriteSqlFragment` (`asWriteSql`): subtype of `SafeSqlFragment` propagated through `safeSql` and `joinSqlFragments`; `executeSql` requires a write grant (or `Unguarded`) to run it. - `UntrustedSqlFragment`: externally influenceable SQL (URL params, LLM output, saved snippets), marked with `untrustedSql(raw)`. - `DisplayableSqlFragment`: union `SafeSqlFragment | UntrustedSqlFragment` — safe to display in the UI, not to execute. - **Never cast `as SafeSqlFragment`** — even redundantly on a `safeSql` template literal (which already returns `SafeSqlFragment`). Assertions bypass provenance tracking; the sole narrow exception is promoting catalog definitions directly inside a data fetcher (below). ### Building safe fragments Compose hardcoded SQL with `safeSql` and sanitize every dynamic value using `@supabase/pg-meta` helpers: - `safeSql` — tagged template accepting only `SafeSqlFragment` interpolations - `ident` — sanitizes identifiers (schema, table, column names) - `literal` — sanitizes literal values - `keyword` — sanitizes SQL keywords - `joinSqlFragments` (`@supabase/pg-meta`) & `trimSafeSqlFragment` (`apps/studio/lib/sql.ts`) — safe fragment manipulation ```ts import { ident, literal, safeSql } from '@supabase/pg-meta' // ✅ GOOD: hardcoded SQL + sanitized interpolations const sql = safeSql` SELECT * FROM ${ident(userInputTableName)} WHERE search_column = ${literal(userInputSearchString)} ` // 🛑 BAD: raw string interpolation fails to typecheck const bad = safeSql`SELECT * FROM ${'my_table'}` ``` ### User-authored input (`SafeSqlInput`) Third-party values can contaminate user inputs if a raw `` is prefilled from URL params or plain strings. Use `SafeSqlInput` (`apps/studio/components/ui/SafeSqlInput.tsx`), which requires `SafeSqlFragment` for `value` and `placeholder` and promotes user keystrokes via `rawSql`. `SafeSqlInput` is essentially the **only** valid use of `rawSql`. ```tsx import { safeSql, type SafeSqlFragment } from '@supabase/pg-meta' import { SafeSqlInput } from '@/components/ui/SafeSqlInput' // ✅ GOOD: value and placeholder are SafeSqlFragment; onChange yields SafeSqlFragment function SafeExpressionField() { const [sql, setSql] = useState(safeSql``) return ( setSql(value)} /> ) } // 🛑 BAD: raw mixes plain strings with SafeSqlFragment // setSql(e.target.value)} /> ``` ### Round-tripped database SQL vs user snippets - **Catalog definitions** (function definitions, RLS expressions, views) returned directly from the database may be promoted **only at the fetch boundary** inside `apps/studio/data/**/*.ts` — never in shared `utils.ts` or components where provenance cannot be verified. - **User snippets are ALWAYS UNSAFE**: snippets are auto-persisted and externally influenceable (e.g. prefilled from URL params). Their `unchecked_sql` field is typed `UntrustedSqlFragment` — never cast it and never auto-run it. ```ts // ✅ GOOD (see apps/studio/data/database-functions/database-functions-query.ts): // promote catalog SQL directly at the fetch boundary export async function getDatabaseFunctions(...) { const { result } = await executeSql(...) return result as SavedDatabaseFunction[] } // 🛑 BAD: promoting in a shared utils.ts or component hides where the string came from ``` ### Promoting non-sanitizable SQL (`acceptUntrustedSql`) Arbitrary SQL that cannot be sanitized with `ident`/`literal`/`keyword` (such as snippet `unchecked_sql` or an RLS `USING` expression) can be promoted with `acceptUntrustedSql` (`@supabase/pg-meta`) **only inside an explicit user-action event handler** (e.g. clicking Run). Never call `acceptUntrustedSql` in `useQuery`, `useEffect`, render, or any automatic path. ```tsx import { acceptUntrustedSql } from '@supabase/pg-meta' import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation' import { useGrant } from '@/lib/grants' import type { SqlSnippets, UserContent } from '@/types/userContent' function SnippetRunner({ projectRef, connectionString, snippet, }: { projectRef: string connectionString?: string | null snippet: UserContent }) { const writeGrant = useGrant( 'POST /platform/pg-meta/{ref}/query', { projectRef }, { variant: 'write' } ) const { mutate: execute } = useExecuteSqlMutation() // ✅ GOOD: promoted inside a click handler after the user sees and chooses to run the SQL const handleRun = () => { if (!writeGrant.grant) return execute({ projectRef, connectionString, sql: acceptUntrustedSql(snippet.content.unchecked_sql), sqlOrigin: 'user', grant: writeGrant.grant, }) } return ( ) } // 🛑 BAD: auto-running in useQuery/useEffect or casting bypasses user confirmation // useQuery({ queryKey: [...], queryFn: () => executeSql({ projectRef, connectionString, sql: acceptUntrustedSql(sql), sqlOrigin: 'user', grant }) }) // useEffect(() => { execute({ projectRef, connectionString, sql: snippet.content.unchecked_sql as SafeSqlFragment, sqlOrigin: 'user', grant }) }, [snippet]) ``` --- ## Analytics SQL (BigQuery / ClickHouse) The same provenance model applies to analytics queries targeting `/platform/projects/{ref}/analytics/endpoints/logs.all{,.otel}`. - **Disjoint brand**: `SafeLogSqlFragment` (`apps/studio/data/logs/safe-analytics-sql.ts`) is separate from pg-meta's `SafeSqlFragment` because escape semantics differ (`E'…'`, `::jsonb`, and double-quoted identifiers are unsafe in BigQuery/ClickHouse, and vice versa). Crossing brands fails at compile time. Never cast `as SafeLogSqlFragment`. - **Wire boundary**: `executeAnalyticsSql` (`apps/studio/data/logs/execute-analytics-sql.ts`) accepts only `SafeLogSqlFragment`. An ESLint `no-restricted-syntax` rule in `apps/studio/eslint.config.cjs` catches direct `post()`/`get()` calls with string-literal `logs.all` / `logs.all.otel` URLs outside `execute-analytics-sql.ts` (indirect calls via `logsAllEndpointUrl(...)` are not caught by lint, so always route through `executeAnalyticsSql`). ### Helpers (`apps/studio/data/logs/safe-analytics-sql.ts`) - `safeSql` — tagged template accepting only `SafeLogSqlFragment` interpolations (rejects plain strings and Postgres `SafeSqlFragment`) - `analyticsLiteral(value)` — escapes string (`''`, `\\`), number, or boolean literals - `quotedIdent(value)` — validates `[A-Za-z_][A-Za-z0-9_]*` segments and backtick-quotes dotted identifiers - `keyword(value, allowed)` — resolves against an allow-list of pre-branded fragments (e.g. `AND`/`OR`); never returns raw input - `joinSqlFragments(fragments, separator)` — composes branded fragments with fixed structural separators ```ts import { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql' import { analyticsLiteral, quotedIdent, safeSql } from '@/data/logs/safe-analytics-sql' // ✅ GOOD: every dynamic interpolation is sanitized const sql = safeSql` SELECT timestamp, event_message FROM ${quotedIdent(table)} WHERE id = ${analyticsLiteral(id)} ` await executeAnalyticsSql({ projectRef, endpoint, sql, iso_timestamp_start, iso_timestamp_end }) // 🛑 BAD: raw string fails to typecheck at executeAnalyticsSql // const sql = `SELECT * FROM ${table} WHERE id = '${id}'` ``` ### Untrusted editor SQL (`acceptUntrustedLogsSql`) Mark user-authored editor text with `untrustedLogSql(text)` (`UntrustedLogSqlFragment`: displayable and storable, never executable). Promote to `SafeLogSqlFragment` with `acceptUntrustedLogsSql(fragment)` **only** from an explicit run gesture (Run click, Cmd+Enter) or an approval-gated AI notebook tool call — never from render, `useEffect`, or any automatic path. (In `apps/studio/lib/ai/tools/*.server.ts`, ESLint `no-restricted-imports` blocks direct imports of `acceptUntrustedSql`/`acceptUntrustedLogsSql` — receive the promotion gate via `approvalGatedToolFromContract`. The notebook persist path promotes cells solely to satisfy writable storage typing, not as execution approval or precedent for promoting elsewhere.) For ClickHouse query syntax, endpoint/flag selection, and OTEL builders, see [clickhouse-logs-queries](../clickhouse-logs-queries/references/codebase-integration.md).