Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Enable or disable Data API access per table (#41218)

Saxon Fletcher0dab4d93fe11
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 70daf4bde1d..e3e491f304f 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -4,6 +4,10 @@ import { isEmpty, isUndefined, noop } from 'lodash'
import { useState } from 'react'
import { toast } from 'sonner'
+import { useTableApiAccessPrivilegesMutation } from '@/data/privileges/table-api-access-mutation'
+import { useDataApiGrantTogglesEnabled } from '@/hooks/misc/useDataApiGrantTogglesEnabled'
+import { type ApiPrivilegesByRole } from '@/lib/data-api-types'
+import type { DeepReadonly, Prettify } from '@/lib/type-helpers'
import { useParams } from 'common'
import { type GeneratedPolicy } from 'components/interfaces/Auth/Policies/Policies.utils'
import { databasePoliciesKeys } from 'data/database-policies/keys'
@@ -33,7 +37,7 @@ import { usePHFlag } from 'hooks/ui/useFlag'
import { useUrlState } from 'hooks/ui/useUrlState'
import { useTrack } from 'lib/telemetry/track'
import { useGetImpersonatedRoleState } from 'state/role-impersonation-state'
-import { useTableEditorStateSnapshot } from 'state/table-editor'
+import { useTableEditorStateSnapshot, type TableEditorState } from 'state/table-editor'
import { createTabId, useTabsStateSnapshot } from 'state/tabs'
import type { Dictionary } from 'types'
import { SonnerProgress } from 'ui'
@@ -57,6 +61,10 @@ import {
updateTable,
} from './SidePanelEditor.utils'
import { SpreadsheetImport } from './SpreadsheetImport/SpreadsheetImport'
+import {
+ useTableApiAccessHandlerWithHistory,
+ type TableApiAccessParams,
+} from './TableEditor/ApiAccessToggle'
import { TableEditor } from './TableEditor/TableEditor'
import type { ImportContent } from './TableEditor/TableEditor.types'
@@ -89,6 +97,12 @@ type SaveTableParamsExisting = SaveTableParamsBase & {
}
type SaveTablePayloadBase = {
+ /**
+ * Comment to set on the table
+ *
+ * `null` removes existing comment
+ * `undefined` leaves comment unchanged
+ */
comment?: string | null
}
@@ -106,7 +120,7 @@ type SaveTablePayloadExisting = SaveTablePayloadBase & {
rls_enabled?: boolean
}
-type SaveTableConfiguration = {
+type SaveTableConfiguration = Prettify<{
tableId?: number
importContent?: ImportContent
isRLSEnabled: boolean
@@ -114,6 +128,47 @@ type SaveTableConfiguration = {
isDuplicateRows: boolean
existingForeignKeyRelations: ForeignKeyConstraint[]
primaryKey?: Constraint
+}>
+
+const DUMMY_TABLE_API_ACCESS_PARAMS: TableApiAccessParams = {
+ type: 'new',
+}
+
+const createTableApiAccessHandlerParams = ({
+ enabled,
+ snap,
+ selectedTable,
+}: {
+ enabled: boolean
+ snap: DeepReadonly<TableEditorState>
+ selectedTable?: PostgresTable
+}): TableApiAccessParams | undefined => {
+ if (!enabled) return undefined
+
+ const tableSidePanel = snap.sidePanel?.type === 'table' ? snap.sidePanel : undefined
+ if (!tableSidePanel) return undefined
+
+ if (tableSidePanel.mode === 'new') {
+ return {
+ type: 'new',
+ }
+ }
+
+ if (!selectedTable) return undefined
+
+ if (tableSidePanel.mode === 'duplicate') {
+ return {
+ type: 'duplicate',
+ templateSchemaName: selectedTable.schema,
+ templateTableName: selectedTable.name,
+ }
+ }
+
+ return {
+ type: 'edit',
+ schemaName: selectedTable.schema,
+ tableName: selectedTable.name,
+ }
}
export interface SidePanelEditorProps {
@@ -142,6 +197,8 @@ export const SidePanelEditor = ({
const { data: project } = useSelectedProjectQuery()
const { data: org } = useSelectedOrganizationQuery()
const getImpersonatedRoleState = useGetImpersonatedRoleState()
+
+ const isApiGrantTogglesEnabled = useDataApiGrantTogglesEnabled()
const generatePoliciesFlag = usePHFlag<string>('tableCreateGeneratePolicies')
const [isEdited, setIsEdited] = useState<boolean>(false)
@@ -151,6 +208,19 @@ export const SidePanelEditor = ({
connectionString: project?.connectionString,
})
+ const tableApiAccessParams = createTableApiAccessHandlerParams({
+ enabled: isApiGrantTogglesEnabled,
+ snap,
+ selectedTable,
+ })
+ const apiAccessToggleHandler = useTableApiAccessHandlerWithHistory(
+ // Dummy params used to appease TypeScript, actually gated by enabled flag
+ tableApiAccessParams ?? DUMMY_TABLE_API_ACCESS_PARAMS,
+ {
+ enabled: tableApiAccessParams !== undefined,
+ }
+ )
+
const { confirmOnClose, modalProps: closeConfirmationModalProps } = useConfirmOnClose({
checkIsDirty: () => isEdited,
onClose: () => {
@@ -179,6 +249,9 @@ export const SidePanelEditor = ({
const { mutateAsync: updatePublication } = useDatabasePublicationUpdateMutation({
onError: () => {},
})
+ const { mutateAsync: updateApiPrivileges } = useTableApiAccessPrivilegesMutation({
+ onError: () => {}, // Errors handled inline
+ })
const isDuplicating = snap.sidePanel?.type === 'table' && snap.sidePanel.mode === 'duplicate'
@@ -480,6 +553,26 @@ export const SidePanelEditor = ({
}
}
+ const updateTableApiAccess = async (
+ table: RetrieveTableResult,
+ privileges: DeepReadonly<ApiPrivilegesByRole>
+ ) => {
+ if (!project) return console.error('Project is required')
+
+ try {
+ await updateApiPrivileges({
+ projectRef: project.ref,
+ connectionString: project.connectionString ?? undefined,
+ relationId: table.id,
+ privileges,
+ })
+ } catch (error) {
+ const message = error instanceof Error ? error.message : undefined
+ const toastDetail = message ? `: ${message}` : ''
+ toast.error(`Failed to update API access privileges for ${table.name}${toastDetail}`)
+ }
+ }
+
const saveTable = async ({
action,
payload,
@@ -492,6 +585,19 @@ export const SidePanelEditor = ({
let toastId
let saveTableError = false
+ if (isApiGrantTogglesEnabled && !apiAccessToggleHandler.isSuccess) {
+ if (apiAccessToggleHandler.isPending) {
+ toast.info(
+ 'Cannot save table yet because Data API settings are still loading. Please try again in a moment.'
+ )
+ } else {
+ toast.error(
+ 'Cannot save table because there was an error loading Data API settings. Please refresh the page and try again.'
+ )
+ }
+ return
+ }
+
const {
importContent,
isRLSEnabled,
@@ -521,6 +627,15 @@ export const SidePanelEditor = ({
if (isRealtimeEnabled) await updateTableRealtime(table, true)
+ if (isApiGrantTogglesEnabled) {
+ const privilegesToSet = apiAccessToggleHandler.data?.schemaExposed
+ ? apiAccessToggleHandler.data.privileges
+ : undefined
+ if (privilegesToSet) {
+ await updateTableApiAccess(table, privilegesToSet)
+ }
+ }
+
// Invalidate queries for table creation
await Promise.all([
queryClient.invalidateQueries({
@@ -577,6 +692,15 @@ export const SidePanelEditor = ({
})
if (isRealtimeEnabled) await updateTableRealtime(table, isRealtimeEnabled)
+ if (isApiGrantTogglesEnabled) {
+ const privilegesToSet = apiAccessToggleHandler.data?.schemaExposed
+ ? apiAccessToggleHandler.data.privileges
+ : undefined
+ if (privilegesToSet) {
+ await updateTableApiAccess(table, privilegesToSet)
+ }
+ }
+
await Promise.all([
queryClient.invalidateQueries({
queryKey: tableKeys.list(project?.ref, table.schema, includeColumns),
@@ -614,6 +738,14 @@ export const SidePanelEditor = ({
}
if (isTableLike(table)) {
await updateTableRealtime(table, isRealtimeEnabled)
+ if (isApiGrantTogglesEnabled) {
+ const privilegesToSet = apiAccessToggleHandler.data?.schemaExposed
+ ? apiAccessToggleHandler.data.privileges
+ : undefined
+ if (privilegesToSet) {
+ await updateTableApiAccess(table, privilegesToSet)
+ }
+ }
}
if (hasError) {
@@ -761,6 +893,7 @@ export const SidePanelEditor = ({
closePanel={onClosePanel}
saveChanges={saveTable}
updateEditorDirty={() => setIsEdited(true)}
+ apiAccessToggleHandler={apiAccessToggleHandler}
/>
<SchemaEditor
visible={snap.sidePanel?.type === 'schema'}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ApiAccessToggle.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ApiAccessToggle.tsx
new file mode 100644
index 00000000000..2357d328d35
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ApiAccessToggle.tsx
@@ -0,0 +1,493 @@
+import { Settings } from 'lucide-react'
+import Link from 'next/link'
+import {
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type Dispatch,
+ type ReactNode,
+ type SetStateAction,
+} from 'react'
+import { usePreviousDistinct } from 'react-use'
+
+import { useTableApiAccessQuery } from '@/data/privileges/table-api-access-query'
+import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
+import {
+ API_ACCESS_ROLES,
+ API_PRIVILEGE_TYPES,
+ checkDataApiPrivilegesNonEmpty,
+ DEFAULT_DATA_API_PRIVILEGES,
+ EMPTY_DATA_API_PRIVILEGES,
+ isApiPrivilegeType,
+ type ApiAccessRole,
+ type ApiPrivilegesByRole,
+} from '@/lib/data-api-types'
+import type { DeepReadonly, Prettify } from '@/lib/type-helpers'
+import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
+import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
+import { useLoadBalancersQuery } from 'data/read-replicas/load-balancers-query'
+import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
+import { useIsSchemaExposed } from 'hooks/misc/useIsSchemaExposed'
+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
+import { Button, Popover_Shadcn_, PopoverContent_Shadcn_, PopoverTrigger_Shadcn_, Switch } from 'ui'
+import { Admonition } from 'ui-patterns'
+import { Input } from 'ui-patterns/DataInputs/Input'
+import { InfoTooltip } from 'ui-patterns/info-tooltip'
+import {
+ MultiSelector,
+ MultiSelectorContent,
+ MultiSelectorItem,
+ MultiSelectorList,
+ MultiSelectorTrigger,
+} from 'ui-patterns/multi-select'
+
+const ROLE_LABELS: Record<ApiAccessRole, string> = {
+ anon: 'Anonymous (anon)',
+ authenticated: 'Authenticated',
+}
+
+namespace ApiAccessToggleProps {
+ type New = {
+ type: 'new'
+ }
+ type Duplicate = {
+ type: 'duplicate'
+ templateSchemaName: string
+ templateTableName: string
+ }
+ type Edit = {
+ type: 'edit'
+ schemaName: string
+ tableName: string
+ }
+ export type Option = New | Duplicate | Edit
+}
+
+export type TableApiAccessParams = ApiAccessToggleProps.Option
+
+type FetchState<T> =
+ | { isError: true; isPending: false; isSuccess: false; data: undefined }
+ | {
+ isError: false
+ isPending: true
+ isSuccess: false
+ data: undefined
+ }
+ | {
+ isError: false
+ isPending: false
+ isSuccess: true
+ data: Prettify<T>
+ }
+
+type TableApiAccessHandlerResult =
+ | { schemaExposed: false }
+ | {
+ schemaExposed: true
+ privileges: DeepReadonly<ApiPrivilegesByRole>
+ setPrivileges: Dispatch<SetStateAction<DeepReadonly<ApiPrivilegesByRole>>>
+ }
+
+type TableApiAccessHandlerReturn = FetchState<TableApiAccessHandlerResult>
+
+const useTableApiAccessHandler = (
+ params: ApiAccessToggleProps.Option,
+ { enabled = true } = {}
+): TableApiAccessHandlerReturn => {
+ const isNewTable = params.type === 'new'
+ const isDuplicate = params.type === 'duplicate'
+ const isExisting = params.type === 'edit'
+
+ const { selectedSchema } = useQuerySchemaState()
+ const currentTableSchema = isNewTable
+ ? selectedSchema
+ : isDuplicate
+ ? params.templateSchemaName
+ : params.schemaName
+
+ const { data: project } = useSelectedProjectQuery({ enabled })
+ const schemaExposure = useIsSchemaExposed(
+ {
+ projectRef: project?.ref,
+ schemaName: currentTableSchema,
+ },
+ { enabled }
+ )
+
+ const shouldReadExistingGrants = isDuplicate || isExisting
+ const permissionsTemplateSchema = !shouldReadExistingGrants
+ ? undefined
+ : isDuplicate
+ ? params.templateSchemaName
+ : params.schemaName
+ const permissionsTemplateTable = !shouldReadExistingGrants
+ ? undefined
+ : isDuplicate
+ ? params.templateTableName
+ : params.tableName
+ const canResolvePrivilegeParams = Boolean(
+ shouldReadExistingGrants &&
+ project?.ref &&
+ permissionsTemplateSchema &&
+ permissionsTemplateTable
+ )
+ const isPrivilegesQueryEnabled = enabled && canResolvePrivilegeParams
+ const apiAccessStatus = useTableApiAccessQuery(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString ?? undefined,
+ schemaName: permissionsTemplateSchema ?? '',
+ tableNames: permissionsTemplateTable ? [permissionsTemplateTable] : [],
+ },
+ { enabled: isPrivilegesQueryEnabled }
+ )
+
+ const privilegesForTable = permissionsTemplateTable
+ ? apiAccessStatus.data?.[permissionsTemplateTable]
+ : undefined
+
+ const [privileges, setPrivileges] = useState<DeepReadonly<ApiPrivilegesByRole>>(
+ DEFAULT_DATA_API_PRIVILEGES
+ )
+
+ const hasLoadedInitialData = useRef(false)
+
+ const resetState = useStaticEffectEvent(() => {
+ hasLoadedInitialData.current = !shouldReadExistingGrants
+ setPrivileges(DEFAULT_DATA_API_PRIVILEGES)
+ })
+ useEffect(() => {
+ resetState()
+ }, [params.type, selectedSchema, permissionsTemplateSchema, permissionsTemplateTable, resetState])
+
+ const syncApiPrivileges = useStaticEffectEvent(() => {
+ if (hasLoadedInitialData.current) return
+ if (!apiAccessStatus.isSuccess) return
+ if (!privilegesForTable) return
+
+ hasLoadedInitialData.current = true
+ if (privilegesForTable.apiAccessType === 'access') {
+ setPrivileges(privilegesForTable.privileges)
+ } else if (privilegesForTable.apiAccessType === 'exposed-schema-no-grants') {
+ setPrivileges(EMPTY_DATA_API_PRIVILEGES)
+ } else {
+ // Used as a dummy default value but is never exposed since the schema is
+ // not exposed
+ setPrivileges(DEFAULT_DATA_API_PRIVILEGES)
+ }
+ })
+ useEffect(() => {
+ syncApiPrivileges()
+ }, [apiAccessStatus.status, syncApiPrivileges])
+
+ const isPending =
+ !enabled ||
+ schemaExposure.status === 'pending' ||
+ (shouldReadExistingGrants && apiAccessStatus.isPending)
+ if (isPending) {
+ return { isError: false, isPending: true, isSuccess: false, data: undefined }
+ }
+
+ const isError = schemaExposure.isError || (shouldReadExistingGrants && apiAccessStatus.isError)
+ if (isError) {
+ return { isError: true, isPending: false, isSuccess: false, data: undefined }
+ }
+
+ const isSchemaExposed = schemaExposure.data === true
+ if (!isSchemaExposed) {
+ return {
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ data: { schemaExposed: false },
+ }
+ }
+
+ return {
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ data: {
+ schemaExposed: true,
+ privileges,
+ setPrivileges,
+ },
+ }
+}
+
+export type TableApiAccessHandlerWithHistoryReturn = FetchState<
+ TableApiAccessHandlerResult & {
+ clearAllPrivileges: () => void
+ restorePreviousPrivileges: () => void
+ }
+>
+
+export const useTableApiAccessHandlerWithHistory = (
+ params: ApiAccessToggleProps.Option,
+ { enabled = true } = {}
+): TableApiAccessHandlerWithHistoryReturn => {
+ const innerResult = useTableApiAccessHandler(params, { enabled })
+
+ const privileges = innerResult.data?.schemaExposed ? innerResult.data.privileges : undefined
+ const previous = usePreviousDistinct(privileges)
+
+ const clearAllPrivileges = useStaticEffectEvent(() => {
+ if (!innerResult.isSuccess) return
+ if (!innerResult.data.schemaExposed) return
+ innerResult.data?.setPrivileges(EMPTY_DATA_API_PRIVILEGES)
+ })
+
+ const restorePreviousPrivileges = useStaticEffectEvent(() => {
+ if (!innerResult.isSuccess) return
+ if (!innerResult.data.schemaExposed) return
+ innerResult.data?.setPrivileges(previous ?? DEFAULT_DATA_API_PRIVILEGES)
+ })
+
+ if (!innerResult.isSuccess) {
+ return innerResult
+ }
+
+ return {
+ ...innerResult,
+ data: { ...innerResult.data, clearAllPrivileges, restorePreviousPrivileges },
+ }
+}
+
+type ApiAccessToggleProps = {
+ projectRef?: string
+ schemaName?: string
+ tableName?: string
+ handler: TableApiAccessHandlerWithHistoryReturn
+}
+
+export const ApiAccessToggle = ({
+ projectRef,
+ schemaName,
+ tableName,
+ handler,
+}: ApiAccessToggleProps): ReactNode => {
+ const [isPrivilegesPopoverOpen, setIsPrivilegesPopoverOpen] = useState(false)
+
+ const isPending = handler.isPending
+ const isError = handler.isError
+ const isSchemaExposed = handler.data?.schemaExposed
+ const isDisabled = isPending || isError || !isSchemaExposed
+
+ const privileges =
+ handler.isSuccess && handler.data.schemaExposed ? handler.data.privileges : undefined
+ const hasNonEmptyPrivileges = checkDataApiPrivilegesNonEmpty(privileges)
+
+ const handleMasterToggle = (checked: boolean) => {
+ if (!handler.isSuccess) return
+ if (!isSchemaExposed) return
+
+ if (checked) {
+ handler.data?.restorePreviousPrivileges()
+ } else {
+ handler.data?.clearAllPrivileges()
+ }
+ }
+
+ const handlePrivilegesChange = (role: ApiAccessRole) => (values: string[]) => {
+ if (!handler.isSuccess) return
+ if (!isSchemaExposed) return
+ if (!privileges) return
+
+ handler.data?.setPrivileges((oldPrivileges) => {
+ return {
+ ...oldPrivileges,
+ [role]: values.filter(isApiPrivilegeType),
+ }
+ })
+ }
+
+ const totalAvailablePrivileges = API_ACCESS_ROLES.length * API_PRIVILEGE_TYPES.length
+ const totalSelectedPrivileges = Object.values(privileges ?? {}).reduce(
+ (sum, rolePrivileges) => sum + rolePrivileges.length,
+ 0
+ )
+ const hasPartialPrivileges =
+ totalSelectedPrivileges > 0 && totalSelectedPrivileges < totalAvailablePrivileges
+
+ return (
+ <div className="space-y-3">
+ <div className="space-y-3">
+ <div className="flex items-center justify-between gap-3">
+ <div className="space-y-1">
+ <p className="text-sm text-foreground flex items-center gap-1.5">
+ Data API Access
+ <InfoTooltip side="top" className="max-w-80">
+ This controls which operations the <code className="text-xs">anon</code> and{' '}
+ <code className="text-xs">authenticated</code> roles can perform on this table via
+ the Data API. Unselected privileges are revoked from these roles.
+ </InfoTooltip>
+ </p>
+ <p className="text-sm text-foreground-lighter">
+ Allow this table to be queried via Supabase client libraries or the API directly
+ </p>
+ </div>
+ <div className="flex items-center gap-2">
+ <Popover_Shadcn_
+ open={isPrivilegesPopoverOpen}
+ onOpenChange={setIsPrivilegesPopoverOpen}
+ >
+ <PopoverTrigger_Shadcn_ asChild disabled={isDisabled || !hasNonEmptyPrivileges}>
+ <Button type="text" className="w-6 h-6 p-0 text-foreground-light">
+ <Settings strokeWidth={1.5} size={16} />
+ {hasPartialPrivileges && (
+ <span className="absolute right-0 top-0 h-1.5 w-1.5 rounded-full bg-foreground shadow-sm" />
+ )}
+ </Button>
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_ align="end" className="w-[420px] space-y-3">
+ {!isDisabled && (
+ <>
+ <p className="text-sm text-foreground">Adjust API privileges per role</p>
+ <div className="space-y-2">
+ {API_ACCESS_ROLES.map((role) => (
+ <div key={role} className="space-y-2">
+ <p className="text-sm text-foreground flex items-center gap-1.5">
+ {ROLE_LABELS[role]}
+ </p>
+ <MultiSelector
+ values={(privileges?.[role] as string[]) ?? []}
+ onValuesChange={handlePrivilegesChange(role)}
+ >
+ <MultiSelectorTrigger
+ label="Select privileges"
+ badgeLimit={4}
+ deletableBadge={true}
+ />
+ <MultiSelectorContent>
+ <MultiSelectorList>
+ {API_PRIVILEGE_TYPES.map((privilege) => (
+ <MultiSelectorItem key={privilege} value={privilege}>
+ {privilege}
+ </MultiSelectorItem>
+ ))}
+ </MultiSelectorList>
+ </MultiSelectorContent>
+ </MultiSelector>
+ </div>
+ ))}
+ </div>
+ </>
+ )}
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
+ <Switch
+ checked={hasNonEmptyPrivileges}
+ onCheckedChange={handleMasterToggle}
+ disabled={isDisabled}
+ />
+ </div>
+ </div>
+ </div>
+ <SchemaExposureOptions
+ projectRef={projectRef}
+ schemaName={schemaName}
+ tableName={tableName}
+ isPending={isPending}
+ isError={isError}
+ isSchemaExposed={isSchemaExposed}
+ hasNonEmptyPrivileges={!!privileges ? hasNonEmptyPrivileges : undefined}
+ />
+ </div>
+ )
+}
+
+const SchemaExposureOptions = ({
+ projectRef,
+ schemaName,
+ tableName,
+ isPending,
+ isError,
+ isSchemaExposed,
+ hasNonEmptyPrivileges,
+}: {
+ projectRef?: string
+ schemaName?: string
+ tableName?: string
+ isPending: boolean
+ isError: boolean
+ isSchemaExposed?: boolean
+ hasNonEmptyPrivileges?: boolean
+}): ReactNode => {
+ const { selectedDatabaseId } = useDatabaseSelectorStateSnapshot()
+
+ const { data: customDomainData } = useCustomDomainsQuery({ projectRef })
+ const { data: loadBalancers } = useLoadBalancersQuery({ projectRef })
+ const { data: databases } = useReadReplicasQuery({ projectRef })
+
+ const apiEndpoint = useMemo(() => {
+ const isCustomDomainActive = customDomainData?.customDomain?.status === 'active'
+ if (isCustomDomainActive && selectedDatabaseId === projectRef) {
+ return `https://${customDomainData.customDomain.hostname}`
+ }
+
+ const loadBalancerSelected = selectedDatabaseId === 'load-balancer'
+ if (loadBalancerSelected) {
+ return loadBalancers?.[0]?.endpoint
+ }
+
+ const selectedDatabase = databases?.find((db) => db.identifier === selectedDatabaseId)
+ return selectedDatabase?.restUrl
+ }, [
+ projectRef,
+ databases,
+ selectedDatabaseId,
+ customDomainData?.customDomain?.status,
+ customDomainData?.customDomain?.hostname,
+ loadBalancers,
+ ])
+ const apiBaseUrl = useMemo(() => {
+ if (!apiEndpoint) return undefined
+ return apiEndpoint.endsWith('/') ? apiEndpoint.slice(0, -1) : apiEndpoint
+ }, [apiEndpoint])
+
+ const tablePath = !(schemaName && tableName)
+ ? undefined
+ : schemaName === 'public'
+ ? tableName
+ : `${schemaName}.${tableName}`
+ const apiUrl = apiBaseUrl && tablePath ? `${apiBaseUrl}/${tablePath}` : undefined
+
+ return (
+ <>
+ {isError && (
+ <Admonition type="warning" title="An error occurred while fetching Data API settings." />
+ )}
+
+ {isSchemaExposed && apiUrl && hasNonEmptyPrivileges && (
+ <Input
+ copy
+ readOnly
+ className="font-mono text-xs p-3 text-foreground-lighter"
+ value={apiUrl}
+ />
+ )}
+
+ {!isPending && !isError && !isSchemaExposed && (
+ <Admonition
+ type="default"
+ title={`The "${schemaName}" schema is not exposed via the Data API`}
+ description={
+ <>
+ To enable API access for this table, you need to first expose the{' '}
+ <code className="text-xs">{schemaName}</code> schema in your{' '}
+ <Link
+ href={`/project/${projectRef}/settings/api`}
+ className="text-foreground hover:underline"
+ >
+ API settings
+ </Link>
+ .
+ </>
+ }
+ />
+ )}
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/RLSManagement.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/RLSManagement.tsx
index 278d455c5d3..6bbcfd08456 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/RLSManagement.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/RLSManagement.tsx
@@ -25,6 +25,7 @@ interface RLSManagementProps {
foreignKeyRelations?: ForeignKey[] // For new tables
isNewRecord: boolean
isDuplicating: boolean
+ isExposed?: boolean
generatedPolicies?: GeneratedPolicy[]
onRLSUpdate?: (isEnabled: boolean) => void
onGeneratedPoliciesChange?: (policies: GeneratedPolicy[]) => void
@@ -36,6 +37,7 @@ export const RLSManagement = ({
foreignKeyRelations = [],
isNewRecord,
isDuplicating,
+ isExposed,
generatedPolicies = [],
onRLSUpdate,
onGeneratedPoliciesChange,
@@ -162,7 +164,10 @@ export const RLSManagement = ({
<Admonition
// [Joshen] Using CSS to determine visibility here as the onSuccess within ToggleRLSButton doesn't get triggered
// if we dynamically render this component, since this admonition gets unmounted from the DOM once RLS is updated
- className={cn('mb-0', !isNewRecord && !isRLSEnabled ? 'block' : 'hidden')}
+ className={cn(
+ 'mb-0',
+ !isNewRecord && !isRLSEnabled && isExposed !== false ? 'block' : 'hidden'
+ )}
type="warning"
title="Row Level Security is currently disabled"
description="Your table is currently accessible by anyone on the internet. We recommend enabling RLS to restrict access."
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
index 66c325dd7c4..9b71ffaeba8 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
@@ -3,6 +3,8 @@ import { isEmpty, noop } from 'lodash'
import { useContext, useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
+import { useDataApiGrantTogglesEnabled } from '@/hooks/misc/useDataApiGrantTogglesEnabled'
+import { checkDataApiPrivilegesNonEmpty } from '@/lib/data-api-types'
import type { GeneratedPolicy } from 'components/interfaces/Auth/Policies/Policies.utils'
import { DocsButton } from 'components/ui/DocsButton'
import { useDatabasePublicationsQuery } from 'data/database-publications/database-publications-query'
@@ -31,6 +33,7 @@ import { formatForeignKeys } from '../ForeignKeySelector/ForeignKeySelector.util
import type { SaveTableParams } from '../SidePanelEditor'
import type { ColumnField } from '../SidePanelEditor.types'
import { SpreadsheetImport } from '../SpreadsheetImport/SpreadsheetImport'
+import { ApiAccessToggle, type TableApiAccessHandlerWithHistoryReturn } from './ApiAccessToggle'
import ColumnManagement from './ColumnManagement'
import { ForeignKeysManagement } from './ForeignKeysManagement/ForeignKeysManagement'
import { HeaderTitle } from './HeaderTitle'
@@ -61,6 +64,7 @@ export interface TableEditorProps {
closePanel: () => void
saveChanges: (params: SaveTableParams) => void
updateEditorDirty: () => void
+ apiAccessToggleHandler: TableApiAccessHandlerWithHistoryReturn
}
export const TableEditor = ({
@@ -71,6 +75,7 @@ export const TableEditor = ({
closePanel = noop,
saveChanges = noop,
updateEditorDirty = noop,
+ apiAccessToggleHandler,
}: TableEditorProps) => {
const track = useTrack()
const snap = useTableEditorStateSnapshot()
@@ -78,6 +83,8 @@ export const TableEditor = ({
const { realtimeAll: realtimeEnabled } = useIsFeatureEnabled(['realtime:all'])
const { docsRowLevelSecurityGuidePath } = useCustomContent(['docs:row_level_security_guide_path'])
+ const isApiGrantTogglesEnabled = useDataApiGrantTogglesEnabled()
+
const [params, setParams] = useUrlState()
const { data: project } = useSelectedProjectQuery()
const { selectedSchema } = useQuerySchemaState()
@@ -339,6 +346,12 @@ export const TableEditor = ({
if (!tableFields) return null
+ const isApiAccessAndPoliciesSectionShown = isApiGrantTogglesEnabled || generatePoliciesEnabled
+ const isExposed = isApiGrantTogglesEnabled
+ ? !!apiAccessToggleHandler.data?.schemaExposed &&
+ checkDataApiPrivilegesNonEmpty(apiAccessToggleHandler.data.privileges)
+ : undefined
+
return (
<SidePanel
data-testid="table-editor-side-panel"
@@ -542,22 +555,36 @@ export const TableEditor = ({
</>
)}
- {/* [Joshen] Temporarily hide this section if duplicating, as we aren't duplicating policies atm when duplicating tables */}
- {/* We should do this thought, but let's do this in another PR as the current one is already quite big */}
- {generatePoliciesEnabled && !isDuplicating && (
+ {isApiAccessAndPoliciesSectionShown && (
<>
<SidePanel.Separator />
- <SidePanel.Content className="space-y-10 py-6">
- <RLSManagement
- table={table}
- tableFields={tableFields}
- foreignKeyRelations={isNewRecord ? fkRelations : undefined}
- isNewRecord={isNewRecord}
- isDuplicating={isDuplicating}
- generatedPolicies={generatedPolicies}
- onGeneratedPoliciesChange={setGeneratedPolicies}
- onRLSUpdate={(value) => onUpdateField({ isRLSEnabled: value })}
- />
+ <SidePanel.Content className="py-6 space-y-6">
+ {isApiGrantTogglesEnabled && (
+ <ApiAccessToggle
+ projectRef={project?.ref}
+ schemaName={isNewRecord ? selectedSchema : table?.schema}
+ tableName={
+ isNewRecord || isDuplicating ? tableFields.name : tableFields.name || table?.name
+ }
+ handler={apiAccessToggleHandler}
+ />
+ )}
+
+ {/* [Joshen] Temporarily hide this section if duplicating, as we aren't duplicating policies atm when duplicating tables */}
+ {/* We should do this thought, but let's do this in another PR as the current one is already quite big */}
+ {generatePoliciesEnabled && !isDuplicating && (
+ <RLSManagement
+ table={table}
+ tableFields={tableFields}
+ foreignKeyRelations={isNewRecord ? fkRelations : undefined}
+ isNewRecord={isNewRecord}
+ isDuplicating={isDuplicating}
+ isExposed={isExposed}
+ generatedPolicies={generatedPolicies}
+ onGeneratedPoliciesChange={setGeneratedPolicies}
+ onRLSUpdate={(value) => onUpdateField({ isRLSEnabled: value })}
+ />
+ )}
</SidePanel.Content>
</>
)}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types.ts
index 2f068d8b259..5db5952c543 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types.ts
@@ -1,14 +1,15 @@
+import type { Prettify } from '@/lib/type-helpers'
import type { Dictionary } from 'types'
import type { ColumnField } from '../SidePanelEditor.types'
-export interface TableField {
+export type TableField = Prettify<{
id: number
name: string
comment?: string | null
columns: ColumnField[]
isRLSEnabled: boolean
isRealtimeEnabled: boolean
-}
+}>
export interface ImportContent {
file?: File
diff --git a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
index 5b9dcb15732..fd41515e838 100644
--- a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
+++ b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
@@ -472,13 +472,11 @@ const EntityTooltipTrigger = ({
)
}
- // Show warning for tables with RLS enabled but no policies
- if (
- isDataApiExposedBadgeEnabled &&
+ const isRlsEnabledNoPolicies =
entity.type === ENTITY_TYPE.TABLE &&
- apiAccessData?.hasApiAccess &&
+ apiAccessData?.apiAccessType === 'access' &&
tableHasRlsEnabledNoPolicyLint
- ) {
+ if (isDataApiExposedBadgeEnabled && isRlsEnabledNoPolicies) {
return (
<Tooltip>
<TooltipTrigger className="min-w-4" aria-label="Table exposed via Data API">
@@ -492,8 +490,9 @@ const EntityTooltipTrigger = ({
)
}
- // Show globe icon for tables with API access, RLS enabled and policies
- if (isDataApiExposedBadgeEnabled && apiAccessData?.hasApiAccess) {
+ const isApiExposedWithRlsAndPolicies =
+ apiAccessData?.apiAccessType === 'access' && !tableHasRlsEnabledNoPolicyLint
+ if (isDataApiExposedBadgeEnabled && isApiExposedWithRlsAndPolicies) {
return (
<Tooltip>
<TooltipTrigger className="min-w-4" aria-label="Table exposed via Data API">
diff --git a/apps/studio/data/config/project-postgrest-config-query.ts b/apps/studio/data/config/project-postgrest-config-query.ts
index a50c479e685..4c455992003 100644
--- a/apps/studio/data/config/project-postgrest-config-query.ts
+++ b/apps/studio/data/config/project-postgrest-config-query.ts
@@ -5,6 +5,18 @@ import { get, handleError } from 'data/fetchers'
import type { ResponseError, UseCustomQueryOptions } from 'types'
import { configKeys } from './keys'
+/**
+ * Parses the exposed schema string returned from PostgREST config.
+ *
+ * @param schemaString - e.g., `public,graphql_public`
+ */
+export const parseDbSchemaString = (schemaString: string): string[] => {
+ return schemaString
+ .split(',')
+ .map((s) => s.trim())
+ .filter((s) => s.length > 0)
+}
+
export type ProjectPostgrestConfigVariables = {
projectRef?: string
}
diff --git a/apps/studio/data/privileges/table-api-access-mutation.ts b/apps/studio/data/privileges/table-api-access-mutation.ts
new file mode 100644
index 00000000000..8b49714e4b4
--- /dev/null
+++ b/apps/studio/data/privileges/table-api-access-mutation.ts
@@ -0,0 +1,114 @@
+import pgMeta from '@supabase/pg-meta'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import {
+ API_ACCESS_ROLES,
+ API_PRIVILEGE_TYPES,
+ type ApiPrivilegesByRole,
+} from '@/lib/data-api-types'
+import type { DeepReadonly } from '@/lib/type-helpers'
+import { executeSql } from 'data/sql/execute-sql-query'
+import type { UseCustomMutationOptions } from 'types'
+import type { ConnectionVars } from '../common.types'
+import { lintKeys } from '../lint/keys'
+import { invalidateTablePrivilegesQuery } from './table-privileges-query'
+
+export type TableApiAccessPrivilegesVariables = ConnectionVars & {
+ relationId: number
+ privileges: DeepReadonly<ApiPrivilegesByRole>
+}
+
+export async function updateTableApiAccessPrivileges({
+ projectRef,
+ connectionString,
+ relationId,
+ privileges,
+}: TableApiAccessPrivilegesVariables) {
+ const sqlStatements: string[] = []
+
+ for (const role of API_ACCESS_ROLES) {
+ const rolePrivileges = privileges[role]
+
+ // Determine which privileges to grant and revoke for this role
+ const privilegesToGrant = rolePrivileges
+ const privilegesToRevoke = API_PRIVILEGE_TYPES.filter((p) => !rolePrivileges.includes(p))
+
+ // Revoke privileges that should be removed
+ if (privilegesToRevoke.length > 0) {
+ const revokeGrants = privilegesToRevoke.map((privilegeType) => ({
+ grantee: role,
+ privilegeType,
+ relationId,
+ }))
+ const revokeSql = pgMeta.tablePrivileges.revoke(revokeGrants).sql.trim()
+ if (revokeSql) sqlStatements.push(revokeSql)
+ }
+
+ // Grant privileges that should be added
+ if (privilegesToGrant.length > 0) {
+ const grantGrants = privilegesToGrant.map((privilegeType) => ({
+ grantee: role,
+ privilegeType,
+ relationId,
+ }))
+ const grantSql = pgMeta.tablePrivileges.grant(grantGrants).sql.trim()
+ if (grantSql) sqlStatements.push(grantSql)
+ }
+ }
+
+ if (sqlStatements.length === 0) {
+ return null
+ }
+
+ const { result } = await executeSql<[]>({
+ projectRef,
+ connectionString,
+ sql: sqlStatements.join('\n'),
+ queryKey: ['table-api-access', 'update-privileges'],
+ })
+
+ return result
+}
+
+type UpdateTableApiAccessPrivilegesData = Awaited<ReturnType<typeof updateTableApiAccessPrivileges>>
+
+export const useTableApiAccessPrivilegesMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseCustomMutationOptions<
+ UpdateTableApiAccessPrivilegesData,
+ Error,
+ TableApiAccessPrivilegesVariables
+ >,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<UpdateTableApiAccessPrivilegesData, Error, TableApiAccessPrivilegesVariables>({
+ mutationFn: (vars) => updateTableApiAccessPrivileges(vars),
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+ await Promise.all([
+ invalidateTablePrivilegesQuery(queryClient, projectRef),
+ // This affects the result of the RLS disabled lint, so we need to
+ // invalidate it
+ queryClient.invalidateQueries({
+ queryKey: lintKeys.lint(projectRef),
+ }),
+ ])
+
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to update API access privileges: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/privileges/table-api-access-query.ts b/apps/studio/data/privileges/table-api-access-query.ts
index 5cadf938bf6..585cebb608b 100644
--- a/apps/studio/data/privileges/table-api-access-query.ts
+++ b/apps/studio/data/privileges/table-api-access-query.ts
@@ -1,7 +1,7 @@
import { useMemo } from 'react'
import type { ConnectionVars } from 'data/common.types'
-import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'
+import { useIsSchemaExposed } from 'hooks/misc/useIsSchemaExposed'
import { isApiAccessRole, isApiPrivilegeType, type ApiPrivilegesByRole } from 'lib/data-api-types'
import type { Prettify } from 'lib/type-helpers'
import type { UseCustomQueryOptions } from 'types'
@@ -17,18 +17,6 @@ import {
const STABLE_EMPTY_ARRAY: any[] = []
const STABLE_EMPTY_OBJECT = {}
-/**
- * Parses the exposed schema string returned from PostgREST config.
- *
- * @param schemaString - e.g., `public,graphql_public`
- */
-const parseDbSchemaString = (schemaString: string): string[] => {
- return schemaString
- .split(',')
- .map((s) => s.trim())
- .filter((s) => s.length > 0)
-}
-
const getApiPrivilegesByRole = (
privileges: TablePrivilegesData[number]['privileges']
): ApiPrivilegesByRole => {
@@ -72,32 +60,37 @@ export type UseTableApiAccessQueryParams = Prettify<
}
>
+export type DataApiAccessType = 'none' | 'exposed-schema-no-grants' | 'access'
+
export type TableApiAccessData =
| {
- hasApiAccess: true
+ apiAccessType: 'access'
privileges: ApiPrivilegesByRole
}
| {
- hasApiAccess: false
+ apiAccessType: 'none' | 'exposed-schema-no-grants'
}
-export type TableApiAccessMap = Record<string, TableApiAccessData>
+export type TableApiAccessMap = Prettify<Record<string, TableApiAccessData>>
export type UseTableApiAccessQueryReturn =
| {
data: TableApiAccessMap
+ status: 'success'
isSuccess: true
isPending: false
isError: false
}
| {
data: undefined
+ status: 'pending'
isSuccess: false
isPending: true
isError: false
}
| {
data: undefined
+ status: 'error'
isSuccess: false
isPending: false
isError: true
@@ -118,52 +111,43 @@ export const useTableApiAccessQuery = (
'enabled'
> = {}
): UseTableApiAccessQueryReturn => {
- const {
- data: dbSchemaString,
- isPending: isConfigPending,
- isError: isConfigError,
- } = useProjectPostgrestConfigQuery(
- { projectRef },
- { enabled, select: ({ db_schema }) => db_schema }
- )
- const exposedSchemas = useMemo((): string[] => {
- if (!dbSchemaString) return []
- return parseDbSchemaString(dbSchemaString)
- }, [dbSchemaString])
-
const uniqueTableNames = useMemo(() => {
return new Set(
tableNames.filter((tableName) => typeof tableName === 'string' && tableName.length > 0)
)
}, [tableNames])
const hasTables = uniqueTableNames.size > 0
- const isSchemaExposed = exposedSchemas.includes(schemaName)
- const enablePrivilegesQuery = enabled && isSchemaExposed && hasTables
-
- const {
- data: privileges,
- isPending: isPrivilegesPending,
- isError: isPrivilegesError,
- } = useTablePrivilegesQuery(
+
+ const schemaExposureStatus = useIsSchemaExposed({ projectRef, schemaName }, { enabled })
+ const isSchemaExposed = schemaExposureStatus.isSuccess && schemaExposureStatus.data === true
+
+ const enablePrivilegesQuery = enabled && hasTables
+ const privilegeStatus = useTablePrivilegesQuery(
{ projectRef, connectionString },
{ enabled: enablePrivilegesQuery, ...options }
)
const result: UseTableApiAccessQueryReturn = useMemo(() => {
- const isPending = isConfigPending || (enablePrivilegesQuery && isPrivilegesPending)
+ const isPending =
+ !enabled ||
+ schemaExposureStatus.status === 'pending' ||
+ (enablePrivilegesQuery && privilegeStatus.isPending)
if (isPending) {
return {
data: undefined,
+ status: 'pending',
isSuccess: false,
isPending: true,
isError: false,
}
}
- const isError = isConfigError || (enablePrivilegesQuery && isPrivilegesError)
+ const isError =
+ schemaExposureStatus.status === 'error' || (enablePrivilegesQuery && privilegeStatus.isError)
if (isError) {
return {
data: undefined,
+ status: 'error',
isSuccess: false,
isPending: false,
isError: true,
@@ -173,6 +157,7 @@ export const useTableApiAccessQuery = (
if (!hasTables) {
return {
data: STABLE_EMPTY_OBJECT,
+ status: 'success',
isSuccess: true,
isPending: false,
isError: false,
@@ -181,12 +166,12 @@ export const useTableApiAccessQuery = (
const resultData: TableApiAccessMap = {}
const tablePrivilegesByName = isSchemaExposed
- ? mapPrivilegesByTableName(privileges, schemaName, uniqueTableNames)
+ ? mapPrivilegesByTableName(privilegeStatus.data, schemaName, uniqueTableNames)
: {}
uniqueTableNames.forEach((tableName) => {
if (!isSchemaExposed) {
- resultData[tableName] = { hasApiAccess: false }
+ resultData[tableName] = { apiAccessType: 'none' }
return
}
@@ -196,27 +181,28 @@ export const useTableApiAccessQuery = (
resultData[tableName] = hasAnonOrAuthenticatedPrivileges
? {
- hasApiAccess: true,
+ apiAccessType: 'access',
privileges: tablePrivileges,
}
- : { hasApiAccess: false }
+ : { apiAccessType: 'exposed-schema-no-grants' }
})
return {
data: resultData,
+ status: 'success',
isSuccess: true,
isPending: false,
isError: false,
}
}, [
+ enabled,
enablePrivilegesQuery,
hasTables,
- isConfigError,
- isConfigPending,
- isPrivilegesError,
- isPrivilegesPending,
+ schemaExposureStatus.status,
isSchemaExposed,
- privileges,
+ privilegeStatus.isPending,
+ privilegeStatus.isError,
+ privilegeStatus.data,
schemaName,
uniqueTableNames,
])
diff --git a/apps/studio/hooks/misc/useDataApiGrantTogglesEnabled.ts b/apps/studio/hooks/misc/useDataApiGrantTogglesEnabled.ts
new file mode 100644
index 00000000000..b64dff684d8
--- /dev/null
+++ b/apps/studio/hooks/misc/useDataApiGrantTogglesEnabled.ts
@@ -0,0 +1,14 @@
+import { useFlag } from 'common'
+import { usePHFlag } from '../ui/useFlag'
+
+/**
+ * Determine whether a user has access to Data API grant toggles.
+ *
+ * Requires that the ConfigCat flag for Data API badges and the PostHog flag
+ * for Table Editor API access are both enabled.
+ */
+export const useDataApiGrantTogglesEnabled = (): boolean => {
+ const isDataApiBadgesEnabled = useFlag('dataApiExposedBadge')
+ const isTableEditorApiAccessEnabled = usePHFlag<boolean>('tableEditorApiAccessToggle')
+ return isDataApiBadgesEnabled && !!isTableEditorApiAccessEnabled
+}
diff --git a/apps/studio/hooks/misc/useIsSchemaExposed.ts b/apps/studio/hooks/misc/useIsSchemaExposed.ts
new file mode 100644
index 00000000000..1d4b6c777fa
--- /dev/null
+++ b/apps/studio/hooks/misc/useIsSchemaExposed.ts
@@ -0,0 +1,74 @@
+import { useMemo } from 'react'
+
+import {
+ parseDbSchemaString,
+ useProjectPostgrestConfigQuery,
+} from 'data/config/project-postgrest-config-query'
+
+type UseIsSchemaExposedParams = {
+ projectRef?: string
+ schemaName?: string
+}
+
+type UseIsSchemaExposedOptions = {
+ enabled?: boolean
+}
+
+export type UseIsSchemaExposedReturn =
+ | {
+ status: 'pending'
+ data: undefined
+ isPending: true
+ isError: false
+ isSuccess: false
+ }
+ | {
+ status: 'error'
+ data: undefined
+ isPending: false
+ isError: true
+ isSuccess: false
+ }
+ | {
+ status: 'success'
+ data: boolean
+ isPending: false
+ isError: false
+ isSuccess: true
+ }
+
+export const useIsSchemaExposed = (
+ { projectRef, schemaName }: UseIsSchemaExposedParams,
+ { enabled = true }: UseIsSchemaExposedOptions = {}
+): UseIsSchemaExposedReturn => {
+ const shouldQueryConfig = enabled && !!projectRef && !!schemaName
+ const {
+ data: dbSchemaString,
+ isPending: isConfigPending,
+ isError: isConfigError,
+ } = useProjectPostgrestConfigQuery(
+ { projectRef },
+ { enabled: shouldQueryConfig, select: ({ db_schema }) => db_schema }
+ )
+
+ const exposedSchemas = useMemo(() => {
+ if (!dbSchemaString) return []
+ return parseDbSchemaString(dbSchemaString)
+ }, [dbSchemaString])
+
+ if (!shouldQueryConfig || isConfigPending) {
+ return { status: 'pending', data: undefined, isPending: true, isError: false, isSuccess: false }
+ }
+
+ if (isConfigError) {
+ return { status: 'error', data: undefined, isPending: false, isError: true, isSuccess: false }
+ }
+
+ return {
+ status: 'success',
+ data: exposedSchemas.includes(schemaName),
+ isPending: false,
+ isError: false,
+ isSuccess: true,
+ }
+}
diff --git a/apps/studio/lib/data-api-types.ts b/apps/studio/lib/data-api-types.ts
index 5259530b762..2b2d082ea41 100644
--- a/apps/studio/lib/data-api-types.ts
+++ b/apps/studio/lib/data-api-types.ts
@@ -1,4 +1,5 @@
import type { TablePrivilegesGrant } from 'data/privileges/table-privileges-grant-mutation'
+import type { DeepReadonly } from './type-helpers'
export const API_ACCESS_ROLES = ['anon', 'authenticated'] as const
export type ApiAccessRole = (typeof API_ACCESS_ROLES)[number]
@@ -23,3 +24,20 @@ export const isApiPrivilegeType = (value: string): value is ApiPrivilegeType =>
}
export type ApiPrivilegesByRole = Record<ApiAccessRole, ApiPrivilegeType[]>
+
+export const DEFAULT_DATA_API_PRIVILEGES: DeepReadonly<ApiPrivilegesByRole> = {
+ anon: [...API_PRIVILEGE_TYPES],
+ authenticated: [...API_PRIVILEGE_TYPES],
+}
+
+export const EMPTY_DATA_API_PRIVILEGES: DeepReadonly<ApiPrivilegesByRole> = {
+ anon: [],
+ authenticated: [],
+}
+
+export const checkDataApiPrivilegesNonEmpty = (
+ privileges: DeepReadonly<ApiPrivilegesByRole> | undefined
+): boolean => {
+ if (!privileges) return false
+ return Object.values(privileges).some((privs) => privs.length > 0)
+}
diff --git a/apps/studio/lib/type-helpers.ts b/apps/studio/lib/type-helpers.ts
index 26e2273a496..02b486eac21 100644
--- a/apps/studio/lib/type-helpers.ts
+++ b/apps/studio/lib/type-helpers.ts
@@ -1,3 +1,9 @@
export type PlainObject<Value = unknown> = Record<string | number | symbol, Value>
export type Prettify<T> = { [K in keyof T]: T[K] } & {}
+
+export type DeepReadonly<T> = T extends (infer R)[]
+ ? ReadonlyArray<DeepReadonly<R>>
+ : T extends Object
+ ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
+ : T