Skip to content

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

[FE-2479] chore(studio): revoke default grants in public on project creation (#43704)

Alaister Young49ad1eb325ed
diff --git a/apps/studio/data/privileges/exposed-function-counts-query.ts b/apps/studio/data/privileges/exposed-function-counts-query.ts
index 2cdd0d240e9..e00bb38de04 100644
--- a/apps/studio/data/privileges/exposed-function-counts-query.ts
+++ b/apps/studio/data/privileges/exposed-function-counts-query.ts
@@ -4,6 +4,9 @@ import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError } from 'types'
import { privilegeKeys } from './keys'
+import { INTERNAL_SCHEMAS } from '@/hooks/useProtectedSchemas'
+
+const IGNORED_SCHEMAS = [...INTERNAL_SCHEMAS, 'pg_catalog']
export type ExposedFunctionCountsVariables = {
projectRef?: string
@@ -23,7 +26,7 @@ export async function getExposedFunctionCounts(
if (!projectRef) throw new Error('projectRef is required')
if (!selectedSchemas) throw new Error('selectedSchemas is required')
- const sql = getExposedFunctionCountsSql({ selectedSchemas })
+ const sql = getExposedFunctionCountsSql({ selectedSchemas, ignoredSchemas: IGNORED_SCHEMAS })
const { result } = await executeSql(
{
diff --git a/apps/studio/data/privileges/exposed-table-counts-query.ts b/apps/studio/data/privileges/exposed-table-counts-query.ts
index eb9efbca3d2..b86711d90f3 100644
--- a/apps/studio/data/privileges/exposed-table-counts-query.ts
+++ b/apps/studio/data/privileges/exposed-table-counts-query.ts
@@ -4,6 +4,9 @@ import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError } from 'types'
import { privilegeKeys } from './keys'
+import { INTERNAL_SCHEMAS } from '@/hooks/useProtectedSchemas'
+
+const IGNORED_SCHEMAS = [...INTERNAL_SCHEMAS, 'pg_catalog']
export type ExposedTableCountsVariables = {
projectRef?: string
@@ -23,7 +26,7 @@ export async function getExposedTableCounts(
if (!projectRef) throw new Error('projectRef is required')
if (!selectedSchemas) throw new Error('selectedSchemas is required')
- const sql = getExposedTableCountsSql({ selectedSchemas })
+ const sql = getExposedTableCountsSql({ selectedSchemas, ignoredSchemas: IGNORED_SCHEMAS })
const { result } = await executeSql(
{
diff --git a/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx b/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
index 6bebe8d9309..8f5a4e3b1ad 100644
--- a/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
+++ b/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
@@ -1,8 +1,5 @@
+import { buildDefaultPrivilegesSql } from '@supabase/pg-meta'
import { useParams } from 'common'
-import { ChangeEvent, useEffect, useState } from 'react'
-import { toast } from 'sonner'
-import { Alert, Button, Checkbox, Input, Listbox } from 'ui'
-
import { isVercelUrl } from 'components/interfaces/Integrations/Vercel/VercelIntegration.utils'
import { Markdown } from 'components/interfaces/Markdown'
import VercelIntegrationWindowLayout from 'components/layouts/IntegrationsLayout/VercelIntegrationWindowLayout'
@@ -14,14 +11,18 @@ import { useIntegrationVercelConnectionsCreateMutation } from 'data/integrations
import { useVercelProjectsQuery } from 'data/integrations/integrations-vercel-projects-query'
import { useOrganizationsQuery } from 'data/organizations/organizations-query'
import { useProjectCreateMutation } from 'data/projects/project-create-mutation'
+import { useDataApiGrantTogglesEnabled } from 'hooks/misc/useDataApiGrantTogglesEnabled'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { BASE_PATH, PROVIDERS } from 'lib/constants'
import { getInitialMigrationSQLFromGitHubRepo } from 'lib/integration-utils'
import { passwordStrength, PasswordStrengthScore } from 'lib/password-strength'
import { generateStrongPassword } from 'lib/project'
+import { ChangeEvent, useEffect, useState } from 'react'
import { AWS_REGIONS } from 'shared-data'
+import { toast } from 'sonner'
import { useIntegrationInstallationSnapshot } from 'state/integration-installation'
import type { NextPageWithLayout } from 'types'
+import { Alert, Button, Checkbox, Input, Listbox } from 'ui'
const VercelIntegration: NextPageWithLayout = () => {
return (
@@ -61,6 +62,7 @@ const CreateProject = () => {
const [dbRegion, setDbRegion] = useState(PROVIDERS.AWS.default_region.displayName)
const snapshot = useIntegrationInstallationSnapshot()
+ const isDataApiGrantTogglesEnabled = useDataApiGrantTogglesEnabled()
async function checkPasswordStrength(value: string) {
const { message, strength } = await passwordStrength(value)
@@ -135,19 +137,23 @@ const CreateProject = () => {
snapshot.setLoading(true)
- let dbSql: string | undefined
+ let dbSqlParts: string[] = []
if (shouldRunMigrations) {
const id = toast(`Fetching initial migrations from GitHub repo`)
- dbSql = (await getInitialMigrationSQLFromGitHubRepo(externalId)) ?? undefined
+ const migrationSql = await getInitialMigrationSQLFromGitHubRepo(externalId)
+ if (migrationSql) dbSqlParts.push(migrationSql)
toast.success(`Done fetching initial migrations`, { id })
}
+ if (isDataApiGrantTogglesEnabled) {
+ dbSqlParts.push(buildDefaultPrivilegesSql('revoke'))
+ }
createProject({
organizationSlug: organization.slug,
name: projectName,
dbPass,
dbRegion,
- dbSql,
+ dbSql: dbSqlParts.length > 0 ? dbSqlParts.join('\n') : undefined,
})
}
diff --git a/apps/studio/pages/new/[slug].tsx b/apps/studio/pages/new/[slug].tsx
index c75b49554a0..e6d8b3192ab 100644
--- a/apps/studio/pages/new/[slug].tsx
+++ b/apps/studio/pages/new/[slug].tsx
@@ -1,4 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
+import { buildDefaultPrivilegesSql } from '@supabase/pg-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { LOCAL_STORAGE_KEYS, useFlag, useParams } from 'common'
import { AUTO_ENABLE_RLS_EVENT_TRIGGER_SQL } from 'components/interfaces/Database/Triggers/EventTriggersList/EventTriggers.constants'
@@ -41,19 +42,19 @@ import {
ProjectCreateVariables,
useProjectCreateMutation,
} from 'data/projects/project-create-mutation'
-import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useCustomContent } from 'hooks/custom-content/useCustomContent'
+import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useDataApiGrantTogglesEnabled } from 'hooks/misc/useDataApiGrantTogglesEnabled'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { withAuth } from 'hooks/misc/withAuth'
-import { usePHFlag } from 'hooks/ui/useFlag'
import { DOCS_URL, PROJECT_STATUS, PROVIDERS, useDefaultProvider } from 'lib/constants'
import { buildStudioPageTitle } from 'lib/page-title'
import { useProfile } from 'lib/profile'
import { useTrack } from 'lib/telemetry/track'
-import Link from 'next/link'
import Head from 'next/head'
+import Link from 'next/link'
import { useRouter } from 'next/router'
import { PropsWithChildren, useEffect, useMemo, useState } from 'react'
import { useForm } from 'react-hook-form'
@@ -94,6 +95,7 @@ const Wizard: NextPageWithLayout = () => {
const projectCreationDisabled = useFlag('disableProjectCreationAndUpdate')
const showPostgresVersionSelector = useFlag('showPostgresVersionSelector')
const cloudProviderEnabled = useFlag('enableFlyCloudProvider')
+ const isDataApiGrantTogglesEnabled = useDataApiGrantTogglesEnabled()
const showNonProdFields = process.env.NEXT_PUBLIC_ENVIRONMENT !== 'prod'
const isNotOnHigherPlan = !['team', 'enterprise', 'platform'].includes(currentOrg?.plan.id ?? '')
@@ -326,7 +328,13 @@ const Wizard: NextPageWithLayout = () => {
postgresEngine: useOrioleDb ? availableOrioleVersion?.postgres_engine : postgresEngine,
releaseChannel: useOrioleDb ? availableOrioleVersion?.release_channel : releaseChannel,
...(smartRegionEnabled ? { regionSelection: selectedRegion } : { dbRegion }),
- ...(enableRlsEventTrigger ? { dbSql: AUTO_ENABLE_RLS_EVENT_TRIGGER_SQL } : {}),
+ dbSql:
+ [
+ enableRlsEventTrigger && AUTO_ENABLE_RLS_EVENT_TRIGGER_SQL,
+ isDataApiGrantTogglesEnabled && buildDefaultPrivilegesSql('revoke'),
+ ]
+ .filter(Boolean)
+ .join('\n') || undefined,
}
if (postgresVersion) {
diff --git a/packages/pg-meta/src/sql/studio/privileges.ts b/packages/pg-meta/src/sql/studio/privileges.ts
index 8c3a3c70d07..0b0e5784681 100644
--- a/packages/pg-meta/src/sql/studio/privileges.ts
+++ b/packages/pg-meta/src/sql/studio/privileges.ts
@@ -45,7 +45,7 @@ function getTableGrantsCTEs({
left join pg_roles pr
on pr.oid = acl.grantee
where c.relkind in ('r', 'p', 'v', 'm', 'f')
- and n.nspname not in (${IGNORED_SCHEMAS_LIST})
+ ${IGNORED_SCHEMAS_LIST ? `and n.nspname not in (${IGNORED_SCHEMAS_LIST})` : ''}
${search ? `and (n.nspname || '.' || c.relname) ilike '%${search}%'` : ''}
group by c.oid, n.nspname, c.relname, c.relkind
),
@@ -116,12 +116,18 @@ export function getExposedTablesSql({
`
}
-export function getExposedTableCountsSql({ selectedSchemas }: { selectedSchemas: string[] }) {
+export function getExposedTableCountsSql({
+ selectedSchemas,
+ ignoredSchemas = [],
+}: {
+ selectedSchemas: string[]
+ ignoredSchemas?: string[]
+}) {
const schemasList =
selectedSchemas.length > 0 ? selectedSchemas.map((s) => `'${s}'`).join(', ') : "''"
return /* SQL */ `
- with ${getTableGrantsCTEs()}
+ with ${getTableGrantsCTEs({ ignoredSchemas })}
select
count(*)::int as total_count,
(count(*) filter (where status = 'granted' and schema_name in (${schemasList})))::int as grants_count
@@ -161,7 +167,7 @@ function getFunctionGrantsCTEs({
left join pg_roles pr
on pr.oid = acl.grantee
where p.prokind in ('f', 'w')
- and n.nspname not in (${IGNORED_SCHEMAS_LIST})
+ ${IGNORED_SCHEMAS_LIST ? `and n.nspname not in (${IGNORED_SCHEMAS_LIST})` : ''}
${search ? `and (n.nspname || '.' || p.proname) ilike '%${search}%'` : ''}
group by n.nspname, p.proname
),
@@ -216,12 +222,18 @@ export function getExposedFunctionsSql({
`
}
-export function getExposedFunctionCountsSql({ selectedSchemas }: { selectedSchemas: string[] }) {
+export function getExposedFunctionCountsSql({
+ selectedSchemas,
+ ignoredSchemas = [],
+}: {
+ selectedSchemas: string[]
+ ignoredSchemas?: string[]
+}) {
const schemasList =
selectedSchemas.length > 0 ? selectedSchemas.map((s) => `'${s}'`).join(', ') : "''"
return /* SQL */ `
- with ${getFunctionGrantsCTEs()}
+ with ${getFunctionGrantsCTEs({ ignoredSchemas })}
select
count(*)::int as total_count,
(count(*) filter (where status = 'granted' and schema_name in (${schemasList})))::int as grants_count