safe-sql-execution

SQL-Abfragen sicher gegen eine Benutzerdatenbank ausführen, ohne Risiko von SQL-Injection oder anderen Sicherheitslücken.

npx skills add https://github.com/supabase/supabase --skill safe-sql-execution

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
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 <Input> 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.

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<SafeSqlFragment>(safeSql``)
  return (
    <SafeSqlInput
      placeholder={safeSql`Enter your SQL expression...`}
      value={sql}
      onChange={(_event, value) => setSql(value)}
    />
  )
}

// 🛑 BAD: raw <Input> mixes plain strings with SafeSqlFragment
// <Input placeholder="Enter SQL..." value={sql} onChange={(e) => 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.
// ✅ 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.

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<SqlSnippets.Content>
}) {
  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 (
    <button disabled={!writeGrant.grant} onClick={handleRun}>
      Run
    </button>
  )
}

// 🛑 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
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.

Mehr Skills von supabase

ask-the-docs
supabase
Beantworte Fragen zur Supabase-Dokumentations-App (apps/docs) anhand der dokumentierten Architektur, Build-Pipeline und Review-Pattern-Notizen, und wende Feature-Design…
clickhouse-logs-queries
supabase
Write, review, and migrate Supabase logs queries against the ClickHouse-backed `logs` table (the `logs.all.otel` analytics endpoint). Use this whenever a task…
copywriting
supabase
UI-Texte schreiben oder prüfen (Schaltflächen, Beschriftungen, Leerzustände, Fehlermeldungen, Tooltips, Formulartexte) überall im Monorepo. Laden Sie es, bevor Sie etwas ausliefern oder überprüfen…
dev-toolbar-review
supabase
Verwenden beim Überprüfen von PRs, die packages/dev-tools/, packages/common/posthog-client.ts betreffen.
docs-content
supabase
Schreiben, Bearbeiten, Organisieren und Überprüfen von Supabase-Inhalten überall in apps/docs – Leitfäden, Erklärungen, Tutorials, Fehlerbehebungsbeiträge, Referenzdokumentation und…
e2e-studio-tests
supabase
Führen Sie e2e-Tests in der Studio-App aus. Verwenden Sie, wenn Sie aufgefordert werden, e2e-Tests, Studio-Tests, Playwright-Tests auszuführen oder die Funktion zu testen.
pm-the-docs
supabase
Docs-PM-Entscheidungsunterstützung für den „Write the docs“-Erstellungsprozess — trifft Entscheidungen zu Zielgruppe, Phase und übergreifenden Themenbereichen während der Frame- und Shape-Phasen,…
react-hook-form
supabase
Korrekte React Hook Form-Verwendung überall im Monorepo — Datenfluss, Subscriptions, Reset, Dirty State, Zahlen-Inputs und Regeln für kontrollierte Eingaben. Laden Sie dies…