Files
Charis 115a2ffeef feat(studio): gate database functions, triggers, and webhooks on sql grants (#53269)
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.
2026-11-12 14:58:01 -05:00

425 lines
14 KiB
TypeScript

import { zodResolver } from '@hookform/resolvers/zod'
import { keyword } from '@supabase/pg-meta'
import type { PGTrigger, PGTriggerCreate } from '@supabase/pg-meta'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common'
import { parseAsBoolean, parseAsString, useQueryState } from 'nuqs'
import { useEffect, useRef, useState } from 'react'
import { SubmitHandler, useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { Button, Form, SidePanel } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { FormSchema, WebhookFormValues } from './EditHookPanel.constants'
import { FormContents } from './FormContents'
import { RequiredExtensionsSection } from '@/components/interfaces/Integrations/Integration/RequiredExtensionsSection'
import { useInstallRequiredExtensions } from '@/components/interfaces/Integrations/Integration/useInstallRequiredExtensions'
import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { useDatabaseTriggerCreateMutation } from '@/data/database-triggers/database-trigger-create-mutation'
import { useDatabaseTriggerUpdateMutation } from '@/data/database-triggers/database-trigger-update-transaction-mutation'
import { databaseHooksQueryOptions } from '@/data/database-triggers/database-triggers-query'
import { useHooksEnableMutation } from '@/data/database/hooks-enable-mutation'
import { useSchemasQuery } from '@/data/database/schemas-query'
import { tableEditorQueryOptions } from '@/data/table-editor/table-editor-query'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'
import { isEdgeFunctionUrl } from '@/lib/api/edgeFunctions'
import { getWriteGrantToastMessage, getWriteGrantTooltip, useGrant } from '@/lib/grants'
import { uuidv4 } from '@/lib/helpers'
export type HTTPArgument = { id: string; name: string; value: string }
const FORM_ID = 'edit-hook-panel-form'
const parseHeaders = (selectedHook?: PGTrigger): HTTPArgument[] => {
if (typeof selectedHook === 'undefined') {
return [{ id: uuidv4(), name: 'Content-type', value: 'application/json' }]
}
const [, , headers] = selectedHook.function_args
let parsedHeaders: Record<string, string> = {}
try {
parsedHeaders = JSON.parse(headers.replace(/\\"/g, '"'))
} catch (e) {
parsedHeaders = {}
}
return Object.entries(parsedHeaders).map(([name, value]) => ({
id: uuidv4(),
name,
value,
}))
}
const parseParameters = (selectedHook?: PGTrigger): HTTPArgument[] => {
if (typeof selectedHook === 'undefined') {
return [{ id: uuidv4(), name: '', value: '' }]
}
const [, , , parameters] = selectedHook.function_args
let parsedParameters: Record<string, string> = {}
try {
parsedParameters = JSON.parse(parameters.replace(/\\"/g, '"'))
} catch (e) {
parsedParameters = {}
}
return Object.entries(parsedParameters).map(([name, value]) => ({
id: uuidv4(),
name,
value,
}))
}
export const EditHookPanel = () => {
const { ref } = useParams()
const { data: project } = useSelectedProjectQuery()
const [isLoadingTable, setIsLoadingTable] = useState(false)
const {
requiredExtensionsToInstall,
needsExtensions,
isExtensionDataLoading: isExtensionsLoading,
installRequiredExtensions,
} = useInstallRequiredExtensions()
const { data: schemas, isSuccess: isSchemasLoaded } = useSchemasQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
})
const { mutateAsync: enableHooks } = useHooksEnableMutation({ onError: () => {} })
const needsWebhooksEnabled =
isSchemasLoaded && !schemas.some((schema) => schema.name === 'supabase_functions')
const isExtensionDataLoading = isExtensionsLoading || !isSchemasLoaded
const readGrant = useGrant(
'POST /platform/pg-meta/{ref}/query',
{ projectRef: project?.ref },
{ variant: 'read' }
)
const writeGrant = useGrant(
'POST /platform/pg-meta/{ref}/query',
{ projectRef: project?.ref },
{ variant: 'write' }
)
const { data: hooks = [], isSuccess } = useQuery(
databaseHooksQueryOptions({
projectRef: project?.ref,
connectionString: project?.connectionString,
grant: readGrant.grant,
})
)
const [showCreateHookForm, setShowCreateHookForm] = useQueryState(
'new',
parseAsBoolean.withDefault(false)
)
const [selectedHookIdToEdit, setSelectedHookIdToEdit] = useQueryState(
'edit',
parseAsString.withDefault('')
)
const selectedHook = hooks.find((hook) => hook.id.toString() === selectedHookIdToEdit)
// Webhook IDs aren't stable across edits because the update mutation drops and recreates the
// trigger, assigning a new ID. This causes a brief window where the old selectedHookIdToEdit
// no longer matches any hook, incorrectly triggering the "Webhook not found" toast. Since this
// is an edge case, we use an ad-hoc ref to suppress the toast when the panel is closing rather
// than a more involved solution
const isClosingRef = useRef(false)
const visible = showCreateHookForm || !!selectedHook
const onClose = () => {
isClosingRef.current = true
setShowCreateHookForm(false)
setSelectedHookIdToEdit(null)
}
const { mutate: createDatabaseTrigger, isPending: isCreating } = useDatabaseTriggerCreateMutation(
{
onSuccess: (_, variables) => {
toast.success(`Successfully created new webhook "${variables.payload.name}"`)
onClose()
},
onError: (error) => {
toast.error(`Failed to create webhook: ${error.message}`)
},
}
)
const { mutate: updateDatabaseTrigger, isPending: isUpdating } = useDatabaseTriggerUpdateMutation(
{
onSuccess: (res) => {
toast.success(`Successfully updated webhook "${res.name}"`)
onClose()
},
onError: (error) => {
toast.error(`Failed to update webhook: ${error.message}`)
},
}
)
const isSubmitting = isCreating || isUpdating || isLoadingTable
const restUrl = project?.restUrl
const form = useForm<WebhookFormValues>({
resolver: zodResolver(FormSchema),
defaultValues: {
name: selectedHook?.name ?? '',
table_id: selectedHook?.table_id?.toString() ?? '',
http_url: selectedHook?.function_args?.[0] ?? '',
http_method: (selectedHook?.function_args?.[1] as 'GET' | 'POST') ?? 'POST',
function_type: isEdgeFunctionUrl(selectedHook?.function_args?.[0] ?? '', ref ?? '', restUrl)
? 'supabase_function'
: 'http_request',
timeout_ms: Number(selectedHook?.function_args?.[4] ?? 5000),
events: selectedHook?.events ?? [],
httpHeaders: parseHeaders(selectedHook),
httpParameters: parseParameters(selectedHook),
},
})
useEffect(() => {
if (isSuccess && !!selectedHookIdToEdit && !selectedHook && !isClosingRef.current) {
toast('Webhook not found')
setSelectedHookIdToEdit(null)
}
}, [isSuccess, selectedHook, selectedHookIdToEdit, setSelectedHookIdToEdit])
// Reset the closing ref when the panel fully closes
useEffect(() => {
if (!visible) {
isClosingRef.current = false
}
}, [visible])
// Reset form when panel opens with new selectedHook
useEffect(() => {
if (visible) {
form.reset({
name: selectedHook?.name ?? '',
table_id: selectedHook?.table_id?.toString() ?? '',
http_url: selectedHook?.function_args?.[0] ?? '',
http_method: (selectedHook?.function_args?.[1] as 'GET' | 'POST') ?? 'POST',
function_type: isEdgeFunctionUrl(selectedHook?.function_args?.[0] ?? '', ref ?? '', restUrl)
? 'supabase_function'
: 'http_request',
timeout_ms: Number(selectedHook?.function_args?.[4] ?? 5000),
events: selectedHook?.events ?? [],
httpHeaders: parseHeaders(selectedHook),
httpParameters: parseParameters(selectedHook),
})
}
}, [visible, selectedHook, ref, restUrl, form])
const queryClient = useQueryClient()
const onSubmit: SubmitHandler<WebhookFormValues> = async (values) => {
if (!project?.ref) {
return console.error('Project ref is required')
}
if (!writeGrant.grant) {
toast.error(
getWriteGrantToastMessage(
writeGrant.status,
selectedHook === undefined ? 'create' : 'update',
'webhooks'
)
)
return
}
if (isExtensionDataLoading) return
try {
setIsLoadingTable(true)
if (needsExtensions || needsWebhooksEnabled) {
const toastId = toast.loading('Setting up database webhooks…')
try {
if (needsExtensions) {
const extensionNames = (requiredExtensionsToInstall ?? [])
.map((ext) => ext.name)
.join(', ')
toast.loading(`Installing extensions ${extensionNames}…`, { id: toastId })
await installRequiredExtensions()
}
if (needsWebhooksEnabled) {
toast.loading('Enabling database webhooks…', { id: toastId })
await enableHooks({ ref: project.ref })
}
toast.dismiss(toastId)
} catch (error) {
toast.error(`Failed to set up database webhooks: ${(error as Error).message}`, {
id: toastId,
})
return
}
}
const selectedTable = await queryClient.fetchQuery(
tableEditorQueryOptions({
id: Number(values.table_id),
projectRef: project?.ref,
connectionString: project?.connectionString,
})
)
if (!selectedTable) {
return toast.error('Unable to find selected table')
}
const headers = values.httpHeaders
.filter((header) => header.name && header.value)
.reduce(
(a, b) => {
a[b.name] = b.value
return a
},
{} as Record<string, string>
)
const parameters = values.httpParameters
.filter((param) => param.name && param.value)
.reduce(
(a, b) => {
a[b.name] = b.value
return a
},
{} as Record<string, string>
)
// replacer function with JSON.stringify to handle quotes properly
const stringifiedParameters = JSON.stringify(parameters, (_key, value) => {
if (typeof value === 'string') {
// Return the raw string without any additional escaping
return value
}
return value
})
const payload: PGTriggerCreate = {
events: values.events,
activation: 'AFTER',
orientation: 'ROW',
name: values.name,
table: selectedTable.name,
schema: selectedTable.schema,
function_name: 'http_request',
function_schema: 'supabase_functions',
function_args: [
values.http_url,
values.http_method,
JSON.stringify(headers),
stringifiedParameters,
values.timeout_ms.toString(),
],
}
if (selectedHook === undefined) {
createDatabaseTrigger({
grant: writeGrant.grant,
projectRef: project?.ref,
connectionString: project?.connectionString,
payload,
})
} else {
updateDatabaseTrigger({
grant: writeGrant.grant,
projectRef: project?.ref,
connectionString: project?.connectionString,
originalTrigger: selectedHook,
updatedTrigger: {
...payload,
enabled_mode: 'ORIGIN',
events: payload.events.map(keyword),
},
})
}
} catch (error) {
console.error('Failed to get table editor:', error)
toast.error('Failed to get table editor')
} finally {
setIsLoadingTable(false)
}
}
// This is intentionally kept outside of the useConfirmOnClose hook to force RHF to update the isDirty state.
const isDirty = form.formState.isDirty
const { confirmOnClose, modalProps } = useConfirmOnClose({
checkIsDirty: () => isDirty,
onClose: () => onClose(),
})
return (
<>
<SidePanel
size="xlarge"
visible={visible}
header={
selectedHook === undefined ? (
'Create a new database webhook'
) : (
<span>
Update webhook <code className="text-sm">{selectedHook.name}</code>
</span>
)
}
className="mr-0 transform transition-all duration-300 ease-in-out"
onConfirm={() => {}}
onCancel={confirmOnClose}
customFooter={
<div className="flex w-full justify-end space-x-3 border-t border-default px-3 py-4">
<Button size="tiny" type="button" onClick={confirmOnClose} disabled={isSubmitting}>
Cancel
</Button>
<ButtonTooltip
size="tiny"
variant="primary"
type="submit"
form={FORM_ID}
disabled={isSubmitting || isExtensionDataLoading || !writeGrant.grant}
loading={isSubmitting}
tooltip={{
content: {
side: 'top',
text: getWriteGrantTooltip(
writeGrant.status,
selectedHook === undefined ? 'create' : 'update',
'webhooks'
),
},
}}
>
{selectedHook === undefined ? 'Create webhook' : 'Update webhook'}
</ButtonTooltip>
</div>
}
>
<Form {...form}>
<form id={FORM_ID} onSubmit={form.handleSubmit(onSubmit)}>
<fieldset disabled={!writeGrant.grant} className="contents">
<div className="flex flex-col gap-y-4 border-b px-5 py-5">
{(needsExtensions || needsWebhooksEnabled) && (
<Admonition
type="warning"
title="Database webhooks will be set up"
description="Proceeding will also install the required extensions and enable database webhooks on your project."
/>
)}
<RequiredExtensionsSection hideSeparator />
</div>
<FormContents form={form} selectedHook={selectedHook} />
</fieldset>
</form>
</Form>
</SidePanel>
<DiscardChangesConfirmationDialog {...modalProps} />
</>
)
}