Skip to content

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

Warn when authenticator role overrides exposed schemas (FE-4472) (#50982)

Monica Khoury123c768de169
diff --git a/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx b/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
index e52298e6ff8..770317b3044 100644
--- a/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
+++ b/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
@@ -1,4 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
+import { safeSql } from '@supabase/pg-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common'
@@ -24,6 +25,7 @@ import {
useWatch,
} from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import {
MultiSelector,
@@ -40,14 +42,17 @@ import { ExposedSchemaSelector, internalSchemasCannotExpose } from './ExposedSch
import { HardenAPIModal } from './HardenAPIModal'
import { ExposedFunctionSelector } from '@/components/interfaces/Settings/API/ExposedFunctionSelector'
import { ExposedTableSelector } from '@/components/interfaces/Settings/API/ExposedTableSelector'
+import CopyButton from '@/components/ui/CopyButton'
import { FormActions } from '@/components/ui/Forms/FormActions'
import { useProjectPostgrestConfigQuery } from '@/data/config/project-postgrest-config-query'
import { useProjectPostgrestConfigUpdateMutation } from '@/data/config/project-postgrest-config-update-mutation'
+import { authenticatorRoleConfigQueryOptions } from '@/data/database/authenticator-role-config-query'
import { useSchemasQuery } from '@/data/database/schemas-query'
import { defaultPrivilegesQueryOptions } from '@/data/privileges/default-privileges-query'
import { privilegeKeys } from '@/data/privileges/keys'
import { useUpdateDefaultPrivilegesMutation } from '@/data/privileges/update-default-privileges-mutation'
import { useUpdateExposedEntitiesMutation } from '@/data/privileges/update-exposed-entities-mutation'
+import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useLatest } from '@/hooks/misc/useLatest'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
@@ -55,6 +60,8 @@ import { IS_PLATFORM } from '@/lib/constants'
import { noop } from '@/lib/void'
import type { ResponseError } from '@/types'
+const resetAuthenticatorDbSchemasSql = safeSql`alter role authenticator reset pgrst.db_schemas`
+
const formSchema = z.object({
// Fields for updatePostgrestConfig
dbSchema: z.array(z.string()),
@@ -89,6 +96,7 @@ export const PostgrestConfig = () => {
const queryClient = useQueryClient()
const [showModal, setShowModal] = useState(false)
+ const [showResetOverrideConfirm, setShowResetOverrideConfirm] = useState(false)
const {
data: config,
@@ -116,6 +124,14 @@ export const PostgrestConfig = () => {
})
)
+ const { data: authenticatorDbSchemasOverride, refetch: refetchAuthenticatorRoleConfig } =
+ useQuery(
+ authenticatorRoleConfigQueryOptions({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+ )
+
const configDbSchemas = useMemo(
() => (config?.db_schema ? config.db_schema.split(',').map((x) => x.trim()) : []),
[config?.db_schema]
@@ -131,6 +147,18 @@ export const PostgrestConfig = () => {
onError: noop,
})
+ const { mutate: resetAuthenticatorOverride, isPending: isResettingAuthenticatorOverride } =
+ useExecuteSqlMutation({
+ onSuccess: async () => {
+ toast.success('Reset the authenticator role override')
+ setShowResetOverrideConfirm(false)
+ await refetchAuthenticatorRoleConfig()
+ },
+ onError: (error) => {
+ toast.error(`Failed to reset the authenticator role override: ${error.message}`)
+ },
+ })
+
const [isUpdating, setIsUpdating] = useState(false)
const formId = 'project-postgres-config'
@@ -285,6 +313,16 @@ export const PostgrestConfig = () => {
[watchedDbSchema]
)
+ const isAuthenticatorRoleOverridingSchemas = useMemo(() => {
+ if (!authenticatorDbSchemasOverride) return false
+ // Compared against the persisted config, not the live form selection, so the warning stays
+ // visible until the save actually succeeds rather than disappearing the moment the selector
+ // is edited to match.
+ const saved = new Set(configDbSchemas)
+ const overridden = new Set(authenticatorDbSchemasOverride)
+ return saved.size !== overridden.size || [...saved].some((schema) => !overridden.has(schema))
+ }, [authenticatorDbSchemasOverride, configDbSchemas])
+
return (
<PageSection id="postgrest-config" className="first:pt-0">
<PageSectionContent>
@@ -341,6 +379,45 @@ export const PostgrestConfig = () => {
) : null}
</FormItemLayout>
+ {isAuthenticatorRoleOverridingSchemas && (
+ <Admonition
+ type="warning"
+ title="Exposed schemas are being overridden"
+ description={
+ <>
+ The <code>authenticator</code> role has <code>pgrst.db_schemas</code>{' '}
+ set to{' '}
+ {authenticatorDbSchemasOverride?.map((schema, i) => (
+ <span key={schema}>
+ {i > 0 && ', '}
+ <code>{schema}</code>
+ </span>
+ ))}
+ , which overrides this setting. See the{' '}
+ <a
+ href="https://supabase.com/docs/guides/troubleshooting/pgrst106-the-schema-must-be-one-of-the-following-error-when-querying-an-exposed-schema"
+ target="_blank"
+ rel="noreferrer"
+ className="underline"
+ >
+ PGRST106 troubleshooting guide
+ </a>{' '}
+ to check or reset it.
+ </>
+ }
+ actions={
+ <Button
+ type="button"
+ variant="default"
+ disabled={!canUpdateExposedEntities}
+ onClick={() => setShowResetOverrideConfirm(true)}
+ >
+ Reset override
+ </Button>
+ }
+ />
+ )}
+
<FormItemLayout
isReactForm={false}
layout="flex-row-reverse"
@@ -614,6 +691,41 @@ export const PostgrestConfig = () => {
</PageSectionContent>
{IS_PLATFORM && <HardenAPIModal visible={showModal} onClose={() => setShowModal(false)} />}
+
+ <ConfirmationModal
+ visible={showResetOverrideConfirm}
+ title="Reset authenticator role override?"
+ confirmLabel="Reset override"
+ confirmLabelLoading="Resetting..."
+ loading={isResettingAuthenticatorOverride}
+ onCancel={() => setShowResetOverrideConfirm(false)}
+ onConfirm={() => {
+ if (!projectRef) return
+ resetAuthenticatorOverride({
+ projectRef,
+ connectionString: project?.connectionString,
+ sql: resetAuthenticatorDbSchemasSql,
+ })
+ }}
+ >
+ <p className="text-sm text-foreground-light">
+ This clears the <code>pgrst.db_schemas</code> setting on the <code>authenticator</code>{' '}
+ role, so the Data API falls back to the schemas selected in the Dashboard above.
+ </p>
+ <p className="text-sm text-foreground-light mt-4">The following statement will be run:</p>
+ <div className="relative mt-2">
+ <pre className="px-3 py-2 pr-10 rounded bg-surface-200 text-xs font-mono whitespace-pre-wrap break-words">
+ {resetAuthenticatorDbSchemasSql}
+ </pre>
+ <CopyButton
+ iconOnly
+ type="button"
+ variant="text"
+ className="absolute top-1 right-1"
+ text={resetAuthenticatorDbSchemasSql}
+ />
+ </div>
+ </ConfirmationModal>
</PageSection>
)
}
diff --git a/apps/studio/data/database/authenticator-role-config-query.ts b/apps/studio/data/database/authenticator-role-config-query.ts
new file mode 100644
index 00000000000..b60584bbb67
--- /dev/null
+++ b/apps/studio/data/database/authenticator-role-config-query.ts
@@ -0,0 +1,57 @@
+import { safeSql } from '@supabase/pg-meta'
+import { queryOptions } from '@tanstack/react-query'
+
+import { getAuthenticatorDbSchemasOverride } from './authenticator-role-config-query.utils'
+import { databaseKeys } from './keys'
+import { executeSql } from '@/data/sql/execute-sql-mutation'
+import type { ResponseError } from '@/types'
+
+export type AuthenticatorRoleConfigVariables = {
+ projectRef?: string
+ connectionString?: string | null
+}
+
+const getAuthenticatorRoleConfigSql = safeSql`
+ select rolconfig from pg_roles where rolname = 'authenticator'
+`
+
+export async function getAuthenticatorRoleConfig(
+ { projectRef, connectionString }: AuthenticatorRoleConfigVariables,
+ signal?: AbortSignal
+) {
+ if (!projectRef) throw new Error('projectRef is required')
+
+ const { result } = await executeSql(
+ {
+ projectRef,
+ connectionString,
+ sql: getAuthenticatorRoleConfigSql,
+ queryKey: ['authenticator-role-config'],
+ },
+ signal
+ )
+
+ const rolconfig = (result[0] as { rolconfig: string[] | null } | undefined)?.rolconfig ?? null
+
+ return getAuthenticatorDbSchemasOverride(rolconfig)
+}
+
+export type AuthenticatorRoleConfigData = Awaited<ReturnType<typeof getAuthenticatorRoleConfig>>
+export type AuthenticatorRoleConfigError = ResponseError
+
+export const authenticatorRoleConfigQueryOptions = ({
+ projectRef,
+ connectionString,
+}: AuthenticatorRoleConfigVariables) =>
+ queryOptions({
+ // eslint-disable-next-line @tanstack/query/exhaustive-deps -- connection string doesn't change the result of the query
+ queryKey: databaseKeys.authenticatorRoleConfig(projectRef),
+ queryFn: ({ signal }) => getAuthenticatorRoleConfig({ projectRef, connectionString }, signal),
+ // The fix for this override is usually applied outside the Dashboard (SQL editor, another
+ // client), so there's no cache-invalidation event to react to. Always refetch on mount and
+ // window focus so navigating back to this page (or back to this browser tab) picks up a fix
+ // immediately, instead of silently serving a stale cached result.
+ refetchOnMount: 'always',
+ refetchOnWindowFocus: 'always',
+ enabled: typeof projectRef !== 'undefined',
+ })
diff --git a/apps/studio/data/database/authenticator-role-config-query.utils.test.ts b/apps/studio/data/database/authenticator-role-config-query.utils.test.ts
new file mode 100644
index 00000000000..a6488399cc3
--- /dev/null
+++ b/apps/studio/data/database/authenticator-role-config-query.utils.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest'
+
+import { getAuthenticatorDbSchemasOverride } from './authenticator-role-config-query.utils'
+
+describe('getAuthenticatorDbSchemasOverride', () => {
+ it('returns null when the role has no config set', () => {
+ expect(getAuthenticatorDbSchemasOverride(null)).toBeNull()
+ })
+
+ it('returns null when rolconfig has no pgrst.db_schemas entry', () => {
+ expect(getAuthenticatorDbSchemasOverride(['search_path=public'])).toBeNull()
+ })
+
+ it('parses a single overridden schema', () => {
+ expect(getAuthenticatorDbSchemasOverride(['pgrst.db_schemas=public'])).toEqual(['public'])
+ })
+
+ it('parses multiple overridden schemas', () => {
+ expect(
+ getAuthenticatorDbSchemasOverride([
+ 'search_path=public',
+ 'pgrst.db_schemas=public,custom_schema',
+ ])
+ ).toEqual(['public', 'custom_schema'])
+ })
+
+ it('trims whitespace around schema names', () => {
+ expect(getAuthenticatorDbSchemasOverride(['pgrst.db_schemas=public, custom_schema'])).toEqual([
+ 'public',
+ 'custom_schema',
+ ])
+ })
+})
diff --git a/apps/studio/data/database/authenticator-role-config-query.utils.ts b/apps/studio/data/database/authenticator-role-config-query.utils.ts
new file mode 100644
index 00000000000..d432003506d
--- /dev/null
+++ b/apps/studio/data/database/authenticator-role-config-query.utils.ts
@@ -0,0 +1,26 @@
+/**
+ * Parses a Postgres `rolconfig` array literal (e.g. `{search_path=public,pgrst.db_schemas=public,custom}`)
+ * and returns the schemas set via `pgrst.db_schemas` on the role, if present.
+ *
+ * `ALTER ROLE authenticator SET pgrst.db_schemas = '...'` overrides the Dashboard's "Exposed
+ * schemas" setting at the PostgREST level, so this is used to detect that override.
+ */
+export function getAuthenticatorDbSchemasOverride(rolconfig: string[] | null): string[] | null {
+ if (!rolconfig) return null
+
+ for (const entry of rolconfig) {
+ const separatorIndex = entry.indexOf('=')
+ if (separatorIndex === -1) continue
+
+ const key = entry.slice(0, separatorIndex).trim()
+ if (key !== 'pgrst.db_schemas') continue
+
+ const value = entry.slice(separatorIndex + 1).trim()
+ return value
+ .split(',')
+ .map((schema) => schema.trim())
+ .filter(Boolean)
+ }
+
+ return null
+}
diff --git a/apps/studio/data/database/keys.ts b/apps/studio/data/database/keys.ts
index 82b825ce91b..7d1e515f2f4 100644
--- a/apps/studio/data/database/keys.ts
+++ b/apps/studio/data/database/keys.ts
@@ -72,6 +72,8 @@ export const databaseKeys = {
['projects', projectRef, 'supamonitor-enabled'] as const,
databaseActivity: (projectRef: string | undefined) =>
['projects', projectRef, 'database-activity'] as const,
+ authenticatorRoleConfig: (projectRef: string | undefined) =>
+ ['projects', projectRef, 'authenticator-role-config'] as const,
}
export const getLiveTupleEstimateKey = (