safe-sql-execution
安全地针对用户数据库执行SQL查询,避免SQL注入或其他安全漏洞的风险。
npx skills add https://github.com/supabase/supabase --skill safe-sql-executionSafe 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:
SafeSqlFragmentfrom@supabase/pg-meta→executeSql(apps/studio/data/sql/execute-sql-mutation.ts) - Analytics / Logs SQL:
SafeLogSqlFragmentfromapps/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 viasafeSql, sanitized viaident/literal/keyword, or user-authored viaSafeSqlInput/acceptUntrustedSql).executeSqlrejects plainstringandUntrustedSqlFragmentat compile time.WriteSqlFragment(asWriteSql): subtype ofSafeSqlFragmentpropagated throughsafeSqlandjoinSqlFragments;executeSqlrequires a write grant (orUnguarded) to run it.UntrustedSqlFragment: externally influenceable SQL (URL params, LLM output, saved snippets), marked withuntrustedSql(raw).DisplayableSqlFragment: unionSafeSqlFragment | UntrustedSqlFragment— safe to display in the UI, not to execute.- Never cast
as SafeSqlFragment— even redundantly on asafeSqltemplate literal (which already returnsSafeSqlFragment). 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 onlySafeSqlFragmentinterpolationsident— sanitizes identifiers (schema, table, column names)literal— sanitizes literal valueskeyword— sanitizes SQL keywordsjoinSqlFragments(@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 sharedutils.tsor 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_sqlfield is typedUntrustedSqlFragment— 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'sSafeSqlFragmentbecause escape semantics differ (E'…',::jsonb, and double-quoted identifiers are unsafe in BigQuery/ClickHouse, and vice versa). Crossing brands fails at compile time. Never castas SafeLogSqlFragment. - Wire boundary:
executeAnalyticsSql(apps/studio/data/logs/execute-analytics-sql.ts) accepts onlySafeLogSqlFragment. An ESLintno-restricted-syntaxrule inapps/studio/eslint.config.cjscatches directpost()/get()calls with string-literallogs.all/logs.all.otelURLs outsideexecute-analytics-sql.ts(indirect calls vialogsAllEndpointUrl(...)are not caught by lint, so always route throughexecuteAnalyticsSql).
Helpers (apps/studio/data/logs/safe-analytics-sql.ts)
safeSql— tagged template accepting onlySafeLogSqlFragmentinterpolations (rejects plain strings and PostgresSafeSqlFragment)analyticsLiteral(value)— escapes string ('',\\), number, or boolean literalsquotedIdent(value)— validates[A-Za-z_][A-Za-z0-9_]*segments and backtick-quotes dotted identifierskeyword(value, allowed)— resolves against an allow-list of pre-branded fragments (e.g.AND/OR); never returns raw inputjoinSqlFragments(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.