The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/project secure (#45108)
Saxon Fletcher3b756e4d9f6e
diff --git a/apps/studio/components/interfaces/ProjectHome/AdvisorSection.tsx b/apps/studio/components/interfaces/ProjectHome/AdvisorSection.tsxindex 2875d292ac5..83e5f3c96d7 100644--- a/apps/studio/components/interfaces/ProjectHome/AdvisorSection.tsx+++ b/apps/studio/components/interfaces/ProjectHome/AdvisorSection.tsx@@ -146,7 +146,7 @@ export const AdvisorSection = ({ showEmptyState = false }: { showEmptyState?: boitem.source === 'signal' ? item.summary : isLint ? item.original.detail : ''const cardClasses =item.severity === 'critical'- ? 'border-destructive-400'+ ? 'bg-destructive-200 border-destructive-400': item.severity === 'warning'? 'border-warning-400': ''diff --git a/apps/studio/components/interfaces/ProjectHome/Home.tsx b/apps/studio/components/interfaces/ProjectHome/Home.tsxindex 1c092d9d430..9ca26709731 100644--- a/apps/studio/components/interfaces/ProjectHome/Home.tsx+++ b/apps/studio/components/interfaces/ProjectHome/Home.tsx@@ -13,6 +13,7 @@ import { ProjectUsageSection as ProjectUsageSectionV2 } from './ProjectUsageSectimport { ProjectUsageSection as ProjectUsageSectionV1 } from '@/components/interfaces/Home/ProjectUsageSection'import { SortableSection } from '@/components/interfaces/ProjectHome/SortableSection'import { TopSection } from '@/components/interfaces/ProjectHome/TopSection'+import { ProjectNeedsSecuring } from '@/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring'import { ScaffoldContainer, ScaffoldSection } from '@/components/layouts/Scaffold'import { useLocalStorage } from '@/hooks/misc/useLocalStorage'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'@@ -80,61 +81,72 @@ export const ProjectHome = () => {})return (- <div className="w-full h-full">- <ScaffoldContainer size="large" className={cn(isPaused && 'h-full')}>- <ScaffoldSection- isFullWidth- className={cn(isPaused ? 'h-full flex justify-center !p-0' : 'pb-0')}- >- <TopSection />- </ScaffoldSection>- </ScaffoldContainer>- {!isPaused && (- <ScaffoldContainer size="large">- <ScaffoldSection isFullWidth className="gap-12 pb-32">- <DndContext sensors={sensors} onDragEnd={handleDragEnd}>- <SortableContext items={renderOrder} strategy={verticalListSortingStrategy}>- {renderOrder.map((id) => {- if (IS_PLATFORM && id === 'usage') {- return (- <div key={id} className={cn(isComingUp && 'opacity-60 pointer-events-none')}>- <SortableSection id={id}>- <UsageSection />- </SortableSection>- </div>- )- }- if (id === 'connect' && showConnectSection) {- return (- <SortableSection key={id} id={id}>- <ConnectSection />- </SortableSection>- )- }- if (id === 'advisor') {- return (- <div key={id} className={cn(isComingUp && 'opacity-60 pointer-events-none')}>- <SortableSection id={id}>- <AdvisorSection showEmptyState={isComingUp} />- </SortableSection>- </div>- )- }- if (id === 'custom-report') {- return (- <div key={id} className={cn(isComingUp && 'opacity-60 pointer-events-none')}>- <SortableSection id={id}>- <CustomReportSection />- </SortableSection>- </div>- )- }- })}- </SortableContext>- </DndContext>+ <ProjectNeedsSecuring>+ <div className="w-full h-full">+ <ScaffoldContainer size="large" className={cn(isPaused && 'h-full')}>+ <ScaffoldSection+ isFullWidth+ className={cn(isPaused ? 'h-full flex justify-center !p-0' : 'pb-0')}+ >+ <TopSection /></ScaffoldSection></ScaffoldContainer>- )}- </div>+ {!isPaused && (+ <ScaffoldContainer size="large">+ <ScaffoldSection isFullWidth className="gap-12 pb-32">+ <DndContext sensors={sensors} onDragEnd={handleDragEnd}>+ <SortableContext items={renderOrder} strategy={verticalListSortingStrategy}>+ {renderOrder.map((id) => {+ if (IS_PLATFORM && id === 'usage') {+ return (+ <div+ key={id}+ className={cn(isComingUp && 'opacity-60 pointer-events-none')}+ >+ <SortableSection id={id}>+ <UsageSection />+ </SortableSection>+ </div>+ )+ }+ if (id === 'connect' && showConnectSection) {+ return (+ <SortableSection key={id} id={id}>+ <ConnectSection />+ </SortableSection>+ )+ }+ if (id === 'advisor') {+ return (+ <div+ key={id}+ className={cn(isComingUp && 'opacity-60 pointer-events-none')}+ >+ <SortableSection id={id}>+ <AdvisorSection showEmptyState={isComingUp} />+ </SortableSection>+ </div>+ )+ }+ if (id === 'custom-report') {+ return (+ <div+ key={id}+ className={cn(isComingUp && 'opacity-60 pointer-events-none')}+ >+ <SortableSection id={id}>+ <CustomReportSection />+ </SortableSection>+ </div>+ )+ }+ })}+ </SortableContext>+ </DndContext>+ </ScaffoldSection>+ </ScaffoldContainer>+ )}+ </div>+ </ProjectNeedsSecuring>)}diff --git a/apps/studio/components/layouts/AppLayout/AdvisorButton.tsx b/apps/studio/components/layouts/AppLayout/AdvisorButton.tsxindex 1cd70691b72..c4582ce3297 100644--- a/apps/studio/components/layouts/AppLayout/AdvisorButton.tsx+++ b/apps/studio/components/layouts/AppLayout/AdvisorButton.tsx@@ -47,6 +47,7 @@ export const AdvisorButton = ({ projectRef }: { projectRef?: string }) => {id="advisor-center-trigger"className={cn('rounded-full w-[32px] h-[32px] flex items-center justify-center p-0 group',+ hasCriticalIssues && 'bg-destructive-200 border-destructive-500',isOpen && 'bg-foreground text-background')}onClick={handleClick}diff --git a/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.test.tsx b/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.test.tsxnew file mode 100644index 00000000000..6892203fd98--- /dev/null+++ b/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.test.tsx@@ -0,0 +1,271 @@+import { fireEvent, screen } from '@testing-library/react'+import { mockAnimationsApi } from 'jsdom-testing-mocks'+import type { MouseEventHandler, ReactNode } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { ProjectNeedsSecuring } from './ProjectNeedsSecuring'+import { render } from '@/tests/helpers'++const {+ mockUseFlag,+ mockUseProjectLintsQuery,+ mockUseSelectedProjectQuery,+ mockUseTablesQuery,+ mockUseProjectPostgrestConfigQuery,+ mockUseTablePrivilegesQuery,+ mockUseLocalStorageQuery,+ mockUseRouter,+ mockRouterPush,+} = vi.hoisted(() => ({+ mockUseFlag: vi.fn(),+ mockUseProjectLintsQuery: vi.fn(),+ mockUseSelectedProjectQuery: vi.fn(),+ mockUseTablesQuery: vi.fn(),+ mockUseProjectPostgrestConfigQuery: vi.fn(),+ mockUseTablePrivilegesQuery: vi.fn(),+ mockUseLocalStorageQuery: vi.fn(),+ mockUseRouter: vi.fn(),+ mockRouterPush: vi.fn(),+}))++vi.mock('common', async () => {+ const actual = await vi.importActual<typeof import('common')>('common')++ return {+ ...actual,+ useFlag: mockUseFlag,+ useParams: () => ({ ref: 'project-ref' }),+ }+})++vi.mock('next/router', () => ({+ useRouter: () => mockUseRouter(),+}))++vi.mock('next/link', () => ({+ default: ({+ href,+ children,+ onClick,+ ...props+ }: {+ href: string+ children: ReactNode+ onClick?: MouseEventHandler<HTMLAnchorElement>+ [key: string]: unknown+ }) => (+ <a href={href} onClick={onClick} {...props}>+ {children}+ </a>+ ),+}))++vi.mock('@/data/lint/lint-query', () => ({+ useProjectLintsQuery: mockUseProjectLintsQuery,+}))++vi.mock('@/hooks/misc/useSelectedProject', () => ({+ useSelectedProjectQuery: mockUseSelectedProjectQuery,+}))++vi.mock('@/data/tables/tables-query', () => ({+ useTablesQuery: mockUseTablesQuery,+}))++vi.mock('@/data/config/project-postgrest-config-query', () => ({+ parseDbSchemaString: vi.fn((value: string) => value.split(',').map((schema) => schema.trim())),+ useProjectPostgrestConfigQuery: mockUseProjectPostgrestConfigQuery,+}))++vi.mock('@/data/privileges/table-privileges-query', () => ({+ useTablePrivilegesQuery: mockUseTablePrivilegesQuery,+}))++vi.mock('@/hooks/misc/useLocalStorage', () => ({+ useLocalStorageQuery: mockUseLocalStorageQuery,+}))++vi.mock('sonner', () => ({+ toast: {+ error: vi.fn(),+ },+}))++const issueLint = {+ cache_key: 'lint-1',+ name: 'rls_disabled_in_public',+ detail: 'RLS is disabled on public.invoices',+ description: 'RLS disabled',+ level: 'ERROR',+ categories: ['SECURITY'],+ metadata: {+ schema: 'public',+ name: 'invoices',+ },+}++const tables = [+ {+ id: 1,+ name: 'invoices',+ schema: 'public',+ rls_enabled: false,+ },+ {+ id: 2,+ name: 'profiles',+ schema: 'public',+ rls_enabled: false,+ },+ {+ id: 3,+ name: 'customers',+ schema: 'public',+ rls_enabled: true,+ },+]++const tablePrivileges = [+ {+ schema: 'public',+ name: 'invoices',+ privileges: [+ {+ grantee: 'anon',+ privilege_type: 'SELECT',+ },+ ],+ },+]++describe('ProjectNeedsSecuring', () => {+ beforeEach(() => {+ mockAnimationsApi()+ mockUseFlag.mockReturnValue(true)+ mockUseRouter.mockReturnValue({ pathname: '/project/[ref]', push: mockRouterPush })+ mockUseSelectedProjectQuery.mockReturnValue({+ data: { connectionString: 'postgresql://example' },+ })+ mockUseProjectLintsQuery.mockReturnValue({+ data: [issueLint],+ isPending: false,+ isError: false,+ })+ mockUseTablesQuery.mockReturnValue({+ data: tables,+ isPending: false,+ isError: false,+ })+ mockUseProjectPostgrestConfigQuery.mockReturnValue({+ data: 'public',+ isPending: false,+ isError: false,+ })+ mockUseTablePrivilegesQuery.mockReturnValue({+ data: tablePrivileges,+ isPending: false,+ isError: false,+ })+ mockUseLocalStorageQuery.mockReturnValue([null, vi.fn(), { isLoading: false }])+ })++ afterEach(() => {+ vi.clearAllMocks()+ window.localStorage.clear()+ })++ it('renders the security gate when an exposed table has RLS disabled and the project has not been dismissed', () => {+ render(+ <ProjectNeedsSecuring>+ <div data-testid="project-children">Project content</div>+ </ProjectNeedsSecuring>+ )++ expect(screen.getByText('Your project needs securing')).toBeInTheDocument()+ expect(screen.getByText('Review and fix')).toBeInTheDocument()+ expect(screen.getByRole('link', { name: 'Open Data API settings' })).toHaveAttribute(+ 'href',+ '/project/project-ref/integrations/data_api/settings'+ )+ expect(screen.queryByRole('columnheader', { name: 'Action' })).not.toBeInTheDocument()+ expect(screen.queryByRole('link', { name: 'View policies' })).not.toBeInTheDocument()+ expect(screen.queryByText('profiles')).not.toBeInTheDocument()+ expect(screen.queryByText('customers')).not.toBeInTheDocument()+ expect(screen.getByText('Skip to home')).toBeInTheDocument()+ expect(screen.queryByTestId('project-children')).not.toBeInTheDocument()+ })++ it('navigates to the table policies page when a table row is clicked', () => {+ render(+ <ProjectNeedsSecuring>+ <div data-testid="project-children">Project content</div>+ </ProjectNeedsSecuring>+ )++ fireEvent.click(screen.getByText('invoices'))++ expect(mockRouterPush).toHaveBeenCalledWith(+ '/project/project-ref/auth/policies?schema=public&search=invoices'+ )+ })++ it('renders the project content when the security gate has been dismissed', () => {+ mockUseLocalStorageQuery.mockReturnValue([+ '2026-04-21T00:00:00.000Z',+ vi.fn(),+ { isLoading: false },+ ])++ render(+ <ProjectNeedsSecuring>+ <div data-testid="project-children">Project content</div>+ </ProjectNeedsSecuring>+ )++ expect(screen.queryByText('Your project needs securing')).not.toBeInTheDocument()+ expect(screen.getByTestId('project-children')).toBeInTheDocument()+ })++ it('renders the project content when there are no RLS issues', () => {+ mockUseProjectLintsQuery.mockReturnValue({+ data: [],+ isPending: false,+ isError: false,+ })++ render(+ <ProjectNeedsSecuring>+ <div data-testid="project-children">Project content</div>+ </ProjectNeedsSecuring>+ )++ expect(screen.queryByText('Your project needs securing')).not.toBeInTheDocument()+ expect(screen.getByTestId('project-children')).toBeInTheDocument()+ })++ it('renders the project content on non-home project routes', () => {+ mockUseRouter.mockReturnValue({ pathname: '/project/[ref]/database/tables' })++ render(+ <ProjectNeedsSecuring>+ <div data-testid="project-children">Project content</div>+ </ProjectNeedsSecuring>+ )++ expect(screen.queryByText('Your project needs securing')).not.toBeInTheDocument()+ expect(screen.getByTestId('project-children')).toBeInTheDocument()+ })++ it('renders the project content when the feature flag is disabled', () => {+ mockUseFlag.mockReturnValue(false)++ render(+ <ProjectNeedsSecuring>+ <div data-testid="project-children">Project content</div>+ </ProjectNeedsSecuring>+ )++ expect(screen.queryByText('Your project needs securing')).not.toBeInTheDocument()+ expect(screen.getByTestId('project-children')).toBeInTheDocument()+ })+})diff --git a/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.tsx b/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.tsxnew file mode 100644index 00000000000..35259c472b2--- /dev/null+++ b/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.tsx@@ -0,0 +1,194 @@+import { LOCAL_STORAGE_KEYS, useFlag, useParams } from 'common'+import { AnimatePresence, motion } from 'framer-motion'+import { useRouter } from 'next/router'+import { PropsWithChildren, useMemo } from 'react'++import type {+ ProjectSecurityActionDetails,+ ProjectSecurityActionType,+} from './ProjectNeedsSecuring.types'+import { getExposedSchemas, getTableKey, sortTables } from './ProjectNeedsSecuring.utils'+import { ProjectNeedsSecuringView } from './ProjectNeedsSecuringView'+import { useProjectPostgrestConfigQuery } from '@/data/config/project-postgrest-config-query'+import { useProjectLintsQuery } from '@/data/lint/lint-query'+import { useTablePrivilegesQuery } from '@/data/privileges/table-privileges-query'+import { useTablesQuery } from '@/data/tables/tables-query'+import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+import { isApiAccessRole, isApiPrivilegeType } from '@/lib/data-api-types'+import { useTrack } from '@/lib/telemetry/track'++const PROJECT_SECURITY_FEATURE_FLAG = 'projectNeedsSecuring'+const PROJECT_HOME_PATHNAME = '/project/[ref]'++const ProjectNeedsSecuringGate = ({ children }: PropsWithChildren) => {+ const router = useRouter()+ const track = useTrack()+ const { ref: projectRef } = useParams()+ const { data: project } = useSelectedProjectQuery()++ const [securityDismissedAt, setSecurityDismissedAt, { isLoading: isLoadingDismissedAt }] =+ useLocalStorageQuery<string | null>(+ projectRef+ ? LOCAL_STORAGE_KEYS.PROJECT_SECURITY_DISMISSED_AT(projectRef)+ : 'project-security-dismissed-at-unknown',+ null+ )++ const isProjectHomeRoute = router.pathname === PROJECT_HOME_PATHNAME++ const { data: lints = [], isPending: isLoadingLints } = useProjectLintsQuery(+ { projectRef },+ { enabled: isProjectHomeRoute && !!projectRef }+ )++ const rlsIssueKeys = useMemo(() => {+ return new Set(+ lints+ .filter((lint) => lint.name === 'rls_disabled_in_public' && lint.level === 'ERROR')+ .map((lint) => {+ const schema = typeof lint.metadata?.schema === 'string' ? lint.metadata.schema : null+ const name = typeof lint.metadata?.name === 'string' ? lint.metadata.name : null++ return schema && name ? getTableKey({ schema, name }) : null+ })+ .filter((value): value is string => value !== null)+ )+ }, [lints])++ const hasRlsIssues = rlsIssueKeys.size > 0+ const shouldRenderGate =+ isProjectHomeRoute &&+ !!projectRef &&+ !isLoadingDismissedAt &&+ hasRlsIssues &&+ securityDismissedAt === null++ const {+ data: tables,+ error: tablesError,+ isPending: isLoadingTables,+ } = useTablesQuery(+ {+ projectRef,+ connectionString: project?.connectionString,+ includeColumns: false,+ },+ { enabled: shouldRenderGate }+ )++ const handleTrackAction = (+ type: ProjectSecurityActionType,+ details?: ProjectSecurityActionDetails+ ) => {+ track('project_security_cta_clicked', {+ type,+ ...details,+ })+ }++ const {+ data: dbSchema,+ error: postgrestConfigError,+ isPending: isLoadingPostgrestConfig,+ } = useProjectPostgrestConfigQuery(+ { projectRef },+ {+ enabled: shouldRenderGate,+ select: ({ db_schema }) => db_schema,+ }+ )++ const {+ data: tablePrivileges,+ error: tablePrivilegesError,+ isPending: isLoadingTablePrivileges,+ } = useTablePrivilegesQuery(+ { projectRef, connectionString: project?.connectionString },+ { enabled: shouldRenderGate }+ )++ const tableRows = useMemo(() => {+ if (!tables) return []++ const exposedSchemas = getExposedSchemas(dbSchema)+ const dataApiAccessByTable = new Map<string, boolean>()++ for (const entry of tablePrivileges ?? []) {+ const key = getTableKey(entry)+ const hasDataApiAccess = entry.privileges.some(+ (privilege) =>+ isApiAccessRole(privilege.grantee) && isApiPrivilegeType(privilege.privilege_type)+ )++ if (hasDataApiAccess) {+ dataApiAccessByTable.set(key, true)+ }+ }++ return sortTables(+ tables+ .filter((table) => exposedSchemas.includes(table.schema))+ .filter((table) => !table.rls_enabled && rlsIssueKeys.has(getTableKey(table)))+ .map((table) => {+ const key = getTableKey(table)++ return {+ id: table.id,+ name: table.name,+ schema: table.schema,+ rlsEnabled: table.rls_enabled,+ dataApiAccessible: dataApiAccessByTable.get(key) === true,+ hasRlsIssue: rlsIssueKeys.has(key),+ }+ })+ )+ }, [dbSchema, rlsIssueKeys, tablePrivileges, tables])++ if (!isProjectHomeRoute || !projectRef || isLoadingLints || !hasRlsIssues) {+ return <>{children}</>+ }++ return (+ <AnimatePresence mode="wait">+ {shouldRenderGate ? (+ <motion.div+ key="project-needs-securing"+ className="flex flex-1 min-h-0 w-full"+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ transition={{ duration: 0.2, ease: 'easeOut' }}+ >+ <ProjectNeedsSecuringView+ projectRef={projectRef}+ issueCount={rlsIssueKeys.size}+ tables={tableRows}+ isLoading={isLoadingTables || isLoadingPostgrestConfig || isLoadingTablePrivileges}+ error={tablesError ?? postgrestConfigError ?? tablePrivilegesError}+ onDismiss={() => setSecurityDismissedAt(new Date().toISOString())}+ onTrackAction={handleTrackAction}+ />+ </motion.div>+ ) : (+ <motion.div+ key="project-needs-securing-children"+ className="flex flex-1 min-h-0 w-full"+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ transition={{ duration: 0.2, ease: 'easeOut' }}+ >+ {children}+ </motion.div>+ )}+ </AnimatePresence>+ )+}++export const ProjectNeedsSecuring = ({ children }: PropsWithChildren) => {+ const isEnabled = useFlag(PROJECT_SECURITY_FEATURE_FLAG)++ if (!isEnabled) return <>{children}</>+ return <ProjectNeedsSecuringGate>{children}</ProjectNeedsSecuringGate>+}diff --git a/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.types.ts b/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.types.tsnew file mode 100644index 00000000000..8576ff488b0--- /dev/null+++ b/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.types.ts@@ -0,0 +1,19 @@+export type ProjectSecurityActionType =+ | 'ask_assistant'+ | 'copy_prompt'+ | 'skip_to_home'+ | 'view_policies'++export type ProjectSecurityActionDetails = {+ schema?: string+ tableName?: string+}++export type ProjectSecurityTable = {+ id: number+ name: string+ schema: string+ rlsEnabled: boolean+ dataApiAccessible: boolean+ hasRlsIssue: boolean+}diff --git a/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.utils.ts b/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.utils.tsnew file mode 100644index 00000000000..3fe11ae956e--- /dev/null+++ b/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.utils.ts@@ -0,0 +1,62 @@+import { type ProjectSecurityTable } from './ProjectNeedsSecuring.types'+import { parseDbSchemaString } from '@/data/config/project-postgrest-config-query'++const DEFAULT_EXPOSED_SCHEMA = 'public'++export const getTableKey = ({ schema, name }: { schema: string; name: string }) =>+ `${schema}.${name}`++export const getExposedSchemas = (dbSchema: string | null | undefined) => {+ const schemas = dbSchema ? parseDbSchemaString(dbSchema) : []+ return schemas.length > 0 ? schemas : [DEFAULT_EXPOSED_SCHEMA]+}++export const formatRlsDescription = (count: number) => {+ const isSingular = count === 1+ const noun = isSingular ? 'table' : 'tables'+ const verb = isSingular ? 'has' : 'have'+ const pronoun = isSingular ? 'its' : 'their'++ return `${count} ${noun} ${verb} RLS disabled which means anyone can access ${pronoun} data via the Data API.`+}++export const buildSecurityPromptMarkdown = (issueCount: number, tables: ProjectSecurityTable[]) => {+ const header = [+ '## Project security review',+ '',+ formatRlsDescription(issueCount),+ '',+ '### Tables',+ '',+ '| Table | Schema | Accessible via Data API | RLS |',+ '| --- | --- | --- | --- |',+ ]++ const rows = tables.map(+ (table) =>+ `| ${table.name} | ${table.schema} | ${table.dataApiAccessible ? 'Yes' : 'No'} | ${table.rlsEnabled ? 'Enabled' : 'Disabled'} |`+ )++ const footer = [+ '',+ '### Next step',+ '',+ 'Help me enable RLS on these tables and suggest the minimum policies I should create.',+ ]++ return [...header, ...rows, ...footer].join('\n')+}++export const sortTables = (tables: ProjectSecurityTable[]) => {+ return [...tables].sort((a, b) => {+ const aPriority = a.hasRlsIssue ? 0 : a.rlsEnabled ? 2 : 1+ const bPriority = b.hasRlsIssue ? 0 : b.rlsEnabled ? 2 : 1++ if (aPriority !== bPriority) return aPriority - bPriority++ const schemaComparison = a.schema.localeCompare(b.schema)+ if (schemaComparison !== 0) return schemaComparison++ return a.name.localeCompare(b.name)+ })+}diff --git a/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuringView.tsx b/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuringView.tsxnew file mode 100644index 00000000000..2b45acc614b--- /dev/null+++ b/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuringView.tsx@@ -0,0 +1,234 @@+import { ArrowRight, Check, ExternalLink, Lightbulb, X } from 'lucide-react'+import Link from 'next/link'+import { useRouter } from 'next/router'+import { useMemo } from 'react'+import {+ Button,+ Button_Shadcn_,+ Card,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from 'ui'+import { PageContainer } from 'ui-patterns/PageContainer'+import {+ PageHeader,+ PageHeaderAside,+ PageHeaderDescription,+ PageHeaderIcon,+ PageHeaderMeta,+ PageHeaderSummary,+ PageHeaderTitle,+} from 'ui-patterns/PageHeader'+import {+ PageSection,+ PageSectionAside,+ PageSectionContent,+ PageSectionMeta,+ PageSectionSummary,+ PageSectionTitle,+} from 'ui-patterns/PageSection'+import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'++import type {+ ProjectSecurityActionDetails,+ ProjectSecurityActionType,+ ProjectSecurityTable,+} from './ProjectNeedsSecuring.types'+import {+ buildSecurityPromptMarkdown,+ formatRlsDescription,+ getTableKey,+} from './ProjectNeedsSecuring.utils'+import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { AiAssistantDropdown } from '@/components/ui/AiAssistantDropdown'+import AlertError from '@/components/ui/AlertError'+import { createNavigationHandler } from '@/lib/navigation'+import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'+import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'++const StatusCell = ({ enabled, label }: { enabled: boolean; label: string }) => (+ <div className="flex items-center gap-2 text-sm">+ {enabled ? (+ <Check size={14} className="text-brand" aria-hidden="true" />+ ) : (+ <X size={14} className="text-destructive" aria-hidden="true" />+ )}+ <span>{label}</span>+ </div>+)++export const ProjectNeedsSecuringView = ({+ projectRef,+ issueCount,+ tables,+ isLoading,+ error,+ onDismiss,+ onTrackAction,+}: {+ projectRef: string+ issueCount: number+ tables: ProjectSecurityTable[]+ isLoading: boolean+ error?: { message: string } | null+ onDismiss: () => void+ onTrackAction: (type: ProjectSecurityActionType, details?: ProjectSecurityActionDetails) => void+}) => {+ const router = useRouter()+ const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()++ const promptMarkdown = useMemo(+ () => buildSecurityPromptMarkdown(issueCount, tables),+ [issueCount, tables]+ )++ const handleOpenAssistant = () => {+ onTrackAction('ask_assistant')+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)+ aiSnap.newChat({+ name: 'Review project security',+ initialInput: promptMarkdown,+ })+ }++ return (+ <div className="flex flex-1 flex-col overflow-y-auto">+ <PageHeader size="default">+ <PageHeaderMeta>+ <PageHeaderIcon>+ <div className="shrink-0 w-14 h-14 relative bg-destructive-200 border border-destructive-400 rounded-md flex items-center justify-center">+ <Lightbulb size={20} strokeWidth={1.5} className="text-destructive" />+ </div>+ </PageHeaderIcon>+ <PageHeaderSummary>+ <PageHeaderTitle>Your project needs securing</PageHeaderTitle>+ <PageHeaderDescription>{formatRlsDescription(issueCount)}</PageHeaderDescription>+ </PageHeaderSummary>+ <PageHeaderAside>+ <Button asChild type="text" iconRight={<ArrowRight />}>+ <Link+ href={`/project/${projectRef}`}+ onClick={() => {+ onTrackAction('skip_to_home')+ onDismiss()+ }}+ >+ Skip to home+ </Link>+ </Button>+ </PageHeaderAside>+ </PageHeaderMeta>+ </PageHeader>++ <PageContainer size="default" className="pb-12">+ <PageSection>+ <PageSectionMeta>+ <PageSectionSummary>+ <PageSectionTitle>Review and fix</PageSectionTitle>+ </PageSectionSummary>+ <PageSectionAside>+ <AiAssistantDropdown+ label="Ask Assistant"+ size="tiny"+ buildPrompt={() => promptMarkdown}+ onOpenAssistant={handleOpenAssistant}+ onCopyPrompt={() => onTrackAction('copy_prompt')}+ copyLabel="Copy Markdown"+ disabled={isLoading}+ />+ </PageSectionAside>+ </PageSectionMeta>+ <PageSectionContent>+ {isLoading ? (+ <GenericSkeletonLoader />+ ) : error ? (+ <AlertError+ projectRef={projectRef}+ error={error}+ subject="Failed to retrieve project tables"+ />+ ) : (+ <Card>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Name</TableHead>+ <TableHead>Schema</TableHead>+ <TableHead>+ <div className="flex items-center gap-1.5">+ <span>Accessible via Data API</span>+ <Button_Shadcn_ asChild variant="ghost" size="icon" className="h-6 w-6">+ <Link+ href={`/project/${projectRef}/integrations/data_api/settings`}+ target="_blank"+ rel="noreferrer"+ aria-label="Open Data API settings"+ >+ <ExternalLink size={14} aria-hidden="true" />+ </Link>+ </Button_Shadcn_>+ </div>+ </TableHead>+ <TableHead>RLS</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {tables.map((table) => {+ const policiesHref = `/project/${projectRef}/auth/policies?schema=${table.schema}&search=${table.name}`+ const handleNavigation = createNavigationHandler(policiesHref, router)+ const trackViewPolicies = () =>+ onTrackAction('view_policies', {+ schema: table.schema,+ tableName: table.name,+ })++ return (+ <TableRow+ key={getTableKey(table)}+ className="relative cursor-pointer inset-focus"+ onClick={(event) => {+ trackViewPolicies()+ handleNavigation(event)+ }}+ onAuxClick={(event) => {+ if (event.button === 1) trackViewPolicies()+ handleNavigation(event)+ }}+ onKeyDown={(event) => {+ if (event.key === 'Enter' || event.key === ' ') trackViewPolicies()+ handleNavigation(event)+ }}+ tabIndex={0}+ >+ <TableCell className="font-medium">{table.name}</TableCell>+ <TableCell>{table.schema}</TableCell>+ <TableCell>+ <StatusCell+ enabled={table.dataApiAccessible}+ label={table.dataApiAccessible ? 'Accessible' : 'Not accessible'}+ />+ </TableCell>+ <TableCell>+ <StatusCell+ enabled={table.rlsEnabled}+ label={table.rlsEnabled ? 'Enabled' : 'Disabled'}+ />+ </TableCell>+ </TableRow>+ )+ })}+ </TableBody>+ </Table>+ </Card>+ )}+ </PageSectionContent>+ </PageSection>+ </PageContainer>+ </div>+ )+}diff --git a/apps/studio/components/ui/AiAssistantDropdown.tsx b/apps/studio/components/ui/AiAssistantDropdown.tsxindex f2bd36cd5e8..e3652414c00 100644--- a/apps/studio/components/ui/AiAssistantDropdown.tsx+++ b/apps/studio/components/ui/AiAssistantDropdown.tsx@@ -49,6 +49,7 @@ export interface AiAssistantDropdownProps {label: stringiconOnly?: booleanonOpenAssistant: () => void+ onCopyPrompt?: () => voidtelemetrySource?: TelemetrySourcesize?: ComponentProps<typeof Button>['size']type?: ComponentProps<typeof Button>['type']@@ -67,6 +68,7 @@ export function AiAssistantDropdown({label,iconOnly = false,onOpenAssistant,+ onCopyPrompt,telemetrySource,size = 'tiny',type = 'default',@@ -94,6 +96,7 @@ export function AiAssistantDropdown({copyToClipboard(prompt)setShowCopied(true)setIsOpen(false)+ onCopyPrompt?.()if (telemetrySource) {track('ai_prompt_copied', { source: telemetrySource })diff --git a/packages/common/constants/local-storage.ts b/packages/common/constants/local-storage.tsindex 04ec911b6c3..17c58ad6ddf 100644--- a/packages/common/constants/local-storage.ts+++ b/packages/common/constants/local-storage.ts@@ -97,6 +97,8 @@ export const LOCAL_STORAGE_KEYS = {// RLS event trigger banner dismissedRLS_EVENT_TRIGGER_BANNER_DISMISSED: (ref: string) => `rls-event-trigger-banner-dismissed-${ref}`,+ PROJECT_SECURITY_DISMISSED_AT: (ref: string) => `project-security-dismissed-at-${ref}`,+RLS_TESTER_BANNER_DISMISSED: (ref: string) => `rls-tester-banner-dismissed-${ref}`,// Observability banner dismisseddiff --git a/packages/common/telemetry-constants.ts b/packages/common/telemetry-constants.tsindex ed2d13c7c4d..2546c4da2f3 100644--- a/packages/common/telemetry-constants.ts+++ b/packages/common/telemetry-constants.ts@@ -2763,6 +2763,22 @@ export interface AiExternalToolClickedEvent {groups: TelemetryGroups}+/**+ * User clicked a CTA in the project security gate.+ *+ * @group Events+ * @source studio+ */+export interface ProjectSecurityCtaClickedEvent {+ action: 'project_security_cta_clicked'+ properties: {+ type: 'ask_assistant' | 'copy_prompt' | 'skip_to_home' | 'view_policies'+ schema?: string+ tableName?: string+ }+ groups: TelemetryGroups+}+/*** User opened the request upgrade modal (for users without billing permissions).*@@ -3371,6 +3387,7 @@ export type TelemetryEvent =| AiPromptCopiedEvent| AiAssistantDropdownButtonClickedEvent| AiExternalToolClickedEvent+ | ProjectSecurityCtaClickedEvent| RequestUpgradeModalOpenedEvent| RequestUpgradeSubmittedEvent| DashboardErrorCreatedEvent