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의 다른 스킬

ask-the-docs
supabase
Supabase 문서 앱(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
PR을 검토할 때 사용하세요. packages/dev-tools/, packages/common/posthog-client.ts 파일을 다루는 경우에 해당합니다.
docs-content
supabase
Supabase 콘텐츠를 apps/docs 어디에서든 작성, 편집, 구성, 검토하세요 — 가이드, 설명 자료, 튜토리얼, 문제 해결 항목, 참조 문서 등…
e2e-studio-tests
supabase
Studio 앱에서 e2e 테스트를 실행합니다. e2e 테스트 실행, 스튜디오 테스트 실행, Playwright 테스트 실행, 또는 기능 테스트를 요청받았을 때 사용하세요.
pm-the-docs
supabase
Docs-PM 의사결정 지원 도구로, "Write the docs" 작성 프로세스에서 Frame 및 Shape 단계 중 대상 독자, 단계, 교차 범위 결정을 지원합니다…
react-hook-form
supabase
모노레포 어디서든 올바른 React Hook Form 사용법 — 데이터 흐름, 구독, 리셋, 더티 상태, 숫자 입력, 제어 입력 규칙. 이것을 로드하세요…