mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 15:39:13 +00:00
Resolves FE-4744. Part of the grants rollout; builds on the read/write SQL variants from #53185. ## What - **Data layer:** the database functions, triggers, database webhooks, and event triggers queries now take a `read` grant (exposed as `queryOptions` factories). All 8 create/update/delete mutations take a `write` grant and mark their SQL with `asWriteSql`. - **Guards:** the hand-written FGA checks in the functions, triggers, event triggers, and database webhooks lists, the functions page, the triggers layout/route, and the webhooks integration tab now derive from grants, with denied and error states. - **Other consumers** updated to pass grants: `CreateFunction`, `TriggerSheet`, `EditHookPanel`, `DeleteHookModal`, `ChooseFunctionForm`, `FunctionSelector`, `AutoEnableRLSNotice`, and SQL editor definition/autocomplete hooks. ## Behavior changes - **Webhooks integration tab:** was gated on `database_webhooks_config_read`; now gated on `database_read`, which is what the backend checks for the pg-meta query it uses. Both permissions are granted to the same built-in roles, so there is no change for built-in roles. A permissions-load failure now shows an error alert instead of the content. - **`AutoEnableRLSNotice`:** hidden unless the user has read access, since it can't tell whether the trigger already exists without it. ## Out of scope - User-authored SQL execution in `QueryEditor` / `useSqlEditorExecution` stays `unguarded.migrating` (FE-4750). ## Testing - New tests: query factories and write mutations (`data/database-sql-grants.test.ts`), webhooks tab granted/denied/error, functions list read/write granted/denied/error. - Typecheck, Prettier, lint ratchet, and Studio vitest suites for affected areas pass.
180 lines
5.4 KiB
TypeScript
180 lines
5.4 KiB
TypeScript
import { type SafeSqlFragment } from '@supabase/pg-meta'
|
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
|
import { IS_PLATFORM, useParams } from 'common'
|
|
import { useCallback, useState } from 'react'
|
|
import { toast } from 'sonner'
|
|
|
|
import type { PotentialIssues } from './SQLEditor.types'
|
|
import {
|
|
analyzeQueryIssues,
|
|
buildExecuteParams,
|
|
hasBlockingIssues,
|
|
resolveConnectionString,
|
|
shouldAutoGenerateTitle,
|
|
} from './SQLEditor.utils'
|
|
import { useSQLEditorContext } from './SQLEditorContext'
|
|
import { databaseEventTriggersQueryOptions } from '@/data/database-event-triggers/database-event-triggers-query'
|
|
import { isValidConnString, unguarded } from '@/data/fetchers'
|
|
import { lintKeys } from '@/data/lint/keys'
|
|
import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query'
|
|
import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'
|
|
import { useOrgAiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
|
|
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
|
|
import { useGrant } from '@/lib/grants'
|
|
import { useTrack } from '@/lib/telemetry/track'
|
|
import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
|
|
import { useGetImpersonatedRoleState } from '@/state/role-impersonation-state'
|
|
import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'
|
|
import { getSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'
|
|
|
|
type UseSqlEditorExecutionArgs = {
|
|
id: string
|
|
isDiffOpen: boolean
|
|
hasSelection: boolean
|
|
setAiTitle: (id: string, sql: string) => void
|
|
}
|
|
|
|
export function useSqlEditorExecution({
|
|
id,
|
|
isDiffOpen,
|
|
hasSelection,
|
|
setAiTitle,
|
|
}: UseSqlEditorExecutionArgs) {
|
|
const { ref } = useParams()
|
|
const { editor, clearPendingRunRefocus, refocusEditorAfterRunIfNeeded } = useSQLEditorContext()
|
|
|
|
const { data: project } = useSelectedProjectQuery()
|
|
const queryClient = useQueryClient()
|
|
const track = useTrack()
|
|
const sessionSnap = useSqlEditorSessionSnapshot()
|
|
const limit = sessionSnap.limit
|
|
const databaseSelectorState = useDatabaseSelectorStateSnapshot()
|
|
const getImpersonatedRoleState = useGetImpersonatedRoleState()
|
|
const { aiOptInLevel } = useOrgAiOptInLevel()
|
|
|
|
const { data: databases } = useReadReplicasQuery(
|
|
{ projectRef: ref },
|
|
{ enabled: isValidConnString(project?.connectionString) }
|
|
)
|
|
const readGrant = useGrant(
|
|
'POST /platform/pg-meta/{ref}/query',
|
|
{ projectRef: project?.ref },
|
|
{ variant: 'read' }
|
|
)
|
|
const { data: eventTriggers } = useQuery(
|
|
databaseEventTriggersQueryOptions(
|
|
{
|
|
projectRef: project?.ref,
|
|
connectionString: project?.connectionString,
|
|
grant: readGrant.grant,
|
|
},
|
|
{ enabled: isValidConnString(project?.connectionString) }
|
|
)
|
|
)
|
|
|
|
const [potentialIssues, setPotentialIssues] = useState<PotentialIssues>()
|
|
|
|
const { mutate: execute, isPending: isExecuting } = useExecuteSqlMutation({
|
|
onSuccess(data, vars) {
|
|
if (id) {
|
|
sessionSnap.addResult(id, data.result, vars.autoLimit)
|
|
}
|
|
|
|
// revalidate lint query
|
|
queryClient.invalidateQueries({ queryKey: lintKeys.lint(ref) })
|
|
refocusEditorAfterRunIfNeeded()
|
|
},
|
|
onError(error, vars) {
|
|
if (id) {
|
|
editor.highlightErrorLine(error, hasSelection)
|
|
sessionSnap.addResultError(id, error, vars.autoLimit)
|
|
}
|
|
|
|
refocusEditorAfterRunIfNeeded()
|
|
},
|
|
})
|
|
|
|
const executeQuery = useCallback(
|
|
async (sql: SafeSqlFragment, force: boolean = false) => {
|
|
if (isDiffOpen) {
|
|
clearPendingRunRefocus()
|
|
return
|
|
}
|
|
|
|
if (!editor.isReady() || isExecuting || project === undefined) {
|
|
clearPendingRunRefocus()
|
|
return
|
|
}
|
|
|
|
const issues = analyzeQueryIssues(sql, eventTriggers)
|
|
|
|
if (hasBlockingIssues(issues, force)) {
|
|
setPotentialIssues(issues)
|
|
return
|
|
}
|
|
|
|
// use the latest state for the title-generation check
|
|
const snippet = getSqlEditorV2StateSnapshot().snippets[id]
|
|
if (
|
|
shouldAutoGenerateTitle({
|
|
aiOptInLevel,
|
|
snippetName: snippet?.snippet.name,
|
|
isPlatform: IS_PLATFORM,
|
|
})
|
|
) {
|
|
// Intentionally don't await title gen (lazy)
|
|
setAiTitle(id, sql)
|
|
}
|
|
|
|
editor.clearHighlights()
|
|
|
|
const impersonatedRoleState = getImpersonatedRoleState()
|
|
const connectionString = resolveConnectionString(
|
|
databases,
|
|
databaseSelectorState.selectedDatabaseId
|
|
)
|
|
if (!isValidConnString(connectionString)) {
|
|
clearPendingRunRefocus()
|
|
return toast.error('Unable to run query: Connection string is missing')
|
|
}
|
|
|
|
execute({
|
|
...buildExecuteParams({
|
|
sql,
|
|
limit,
|
|
connectionString,
|
|
projectRef: project.ref,
|
|
impersonatedRoleState,
|
|
}),
|
|
handleError: (error) => {
|
|
throw error
|
|
},
|
|
grant: unguarded.migrating,
|
|
})
|
|
|
|
track('sql_editor_query_run_button_clicked', { source: 'database' })
|
|
},
|
|
[
|
|
editor,
|
|
clearPendingRunRefocus,
|
|
isDiffOpen,
|
|
id,
|
|
isExecuting,
|
|
project,
|
|
aiOptInLevel,
|
|
execute,
|
|
getImpersonatedRoleState,
|
|
setAiTitle,
|
|
databaseSelectorState.selectedDatabaseId,
|
|
databases,
|
|
eventTriggers,
|
|
limit,
|
|
track,
|
|
]
|
|
)
|
|
|
|
const resetPotentialIssues = useCallback(() => setPotentialIssues(undefined), [])
|
|
|
|
return { executeQuery, isExecuting, potentialIssues, resetPotentialIssues }
|
|
}
|