safe-sql-execution

द्वारा supabase

उपयोगकर्ता डेटाबेस पर SQL इंजेक्शन या अन्य सुरक्षा कमजोरियों के जोखिम के बिना सुरक्षित रूप से SQL क्वेरी निष्पादित करें।

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.

supabase की और Skills

ask-the-docs
supabase
प्रलेखित आर्किटेक्चर, बिल्ड पाइपलाइन और समीक्षा-पैटर्न नोट्स का उपयोग करके Supabase docs ऐप (apps/docs) के बारे में प्रश्नों के उत्तर दें, और फीचर-डिज़ाइन लागू करें…
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 कॉपी (बटन, लेबल, खाली स्थितियाँ, त्रुटि संदेश, टूलटिप्स, फ़ॉर्म टेक्स्ट) लिखें या उसकी समीक्षा करें। शिपिंग या समीक्षा से पहले इसे लोड करें…
dev-toolbar-review
supabase
उन PRs की समीक्षा करते समय उपयोग करें जो packages/dev-tools/, packages/common/posthog-client.ts को छूते हैं,
docs-content
supabase
apps/docs में कहीं भी Supabase सामग्री लिखें, संपादित करें, व्यवस्थित करें और समीक्षा करें — गाइड, व्याख्याकार, ट्यूटोरियल, समस्या निवारण प्रविष्टियाँ, संदर्भ दस्तावेज़, और…
e2e-studio-tests
supabase
स्टूडियो ऐप में e2e परीक्षण चलाएँ। जब e2e परीक्षण चलाने, स्टूडियो परीक्षण चलाने, प्लेराइट परीक्षण चलाने, या फीचर का परीक्षण करने के लिए कहा जाए तो इसका उपयोग करें।
pm-the-docs
supabase
Docs-PM "Write the docs" लेखन प्रक्रिया के लिए निर्णय समर्थन — Frame और Shape चरणों के दौरान दर्शकों, चरण और क्रॉस-कटिंग दायरे के निर्णय लेता है,…
react-hook-form
supabase
React Hook Form का सही उपयोग monorepo में कहीं भी — डेटा फ्लो, सब्सक्रिप्शन, रीसेट, डर्टी स्टेट, नंबर इनपुट, और कंट्रोल्ड इनपुट नियम। इसे लोड करें…