The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Feature Preview: RLS Tester (#45121)
Joshen Lim5f867e5f6c47
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsxindex 6cca0e301a7..10be0ebca9a 100644--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx@@ -132,6 +132,13 @@ export const useIsFloatingMobileToolbarEnabled = () => {return showFloatingMobileToolbar && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_FLOATING_MOBILE_TOOLBAR]}+export const useIsRLSTesterEnabled = () => {+ const { flags } = useFeaturePreviewContext()+ const rlsTesterEnabled = useFlag('rlsTester')++ return rlsTesterEnabled && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_TESTER]+}+export const useFeaturePreviewModal = () => {const featurePreviews = useFeaturePreviews()const [featurePreviewModal, setFeaturePreviewModal] = useQueryState('featurePreviewModal')diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsxindex 3083842b1e8..89b00f05886 100644--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx@@ -29,6 +29,7 @@ import { FloatingMobileToolbarPreview } from './FloatingMobileToolbarPreview'import { JitDbAccessPreview } from './JitDbAccessPreview'import { PgDeltaDiffPreview } from './PgDeltaDiffPreview'import { PlatformWebhooksPreview } from './PlatformWebhooksPreview'+import { RLSTesterPreview } from './RLSTesterPreview'import { UnifiedLogsPreview } from './UnifiedLogsPreview'import { FeaturePreview, useFeaturePreviews } from './useFeaturePreviews'import { useSendEventMutation } from '@/data/telemetry/send-event-mutation'@@ -45,6 +46,7 @@ const FEATURE_PREVIEW_KEY_TO_CONTENT: {[LOCAL_STORAGE_KEYS.UI_PREVIEW_PLATFORM_WEBHOOKS]: <PlatformWebhooksPreview />,[LOCAL_STORAGE_KEYS.UI_PREVIEW_JIT_DB_ACCESS]: <JitDbAccessPreview />,[LOCAL_STORAGE_KEYS.UI_PREVIEW_FLOATING_MOBILE_TOOLBAR]: <FloatingMobileToolbarPreview />,+ [LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_TESTER]: <RLSTesterPreview />,}export const FeaturePreviewModal = () => {diff --git a/apps/studio/components/interfaces/App/FeaturePreview/RLSTesterPreview.tsx b/apps/studio/components/interfaces/App/FeaturePreview/RLSTesterPreview.tsxnew file mode 100644index 00000000000..704b0dfd8f1--- /dev/null+++ b/apps/studio/components/interfaces/App/FeaturePreview/RLSTesterPreview.tsx@@ -0,0 +1,38 @@+import { useParams } from 'common'+import Image from 'next/image'++import { InlineLink } from '@/components/ui/InlineLink'+import { BASE_PATH } from '@/lib/constants'++export const RLSTesterPreview = () => {+ const { ref } = useParams()++ return (+ <div className="flex flex-col gap-2">+ <p className="text-foreground-light text-sm mb-4">+ Verify if your RLS policies have been set up properly by running queries as a specific user.+ While role impersonation isn't a new feature on the dashboard, we've built a dedicated UI+ for this which will also show what policies are evaluated for the query.+ </p>+ <Image+ src={`${BASE_PATH}/img/previews/rls-tester-preview.png`}+ width={1296}+ height={900}+ quality={100}+ alt="rls-tester-preview"+ className="rounded border"+ />+ <div className="space-y-2 !mt-4">+ <p className="text-sm">Enabling this preview will:</p>+ <ul className="list-disc pl-6 text-sm text-foreground-light space-y-1">+ <li>+ Show the "Test" button on the{' '}+ <InlineLink href={`/project/${ref}/auth/policies`}>+ Authentication Policies page+ </InlineLink>+ </li>+ </ul>+ </div>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/App/FeaturePreview/useFeaturePreviews.ts b/apps/studio/components/interfaces/App/FeaturePreview/useFeaturePreviews.tsindex 8c9b80f931e..a122fd093cc 100644--- a/apps/studio/components/interfaces/App/FeaturePreview/useFeaturePreviews.ts+++ b/apps/studio/components/interfaces/App/FeaturePreview/useFeaturePreviews.ts@@ -23,8 +23,18 @@ export const useFeaturePreviews = (): FeaturePreview[] => {const showFloatingMobileToolbar = useFlag('enableFloatingMobileToolbar')const platformWebhooksEnabled = useFlag('platformWebhooks')const jitDbAccessEnabled = useFlag('jitDbAccess')+ const rlsTesterEnabled = useFlag('rlsTester')return [+ {+ key: LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_TESTER,+ name: 'RLS Tester',+ discussionsUrl: 'https://github.com/orgs/supabase/discussions/45233',+ enabled: rlsTesterEnabled,+ isNew: true,+ isPlatformOnly: false,+ isDefaultOptIn: false,+ },{key: LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS,name: 'New Logs interface',@@ -48,7 +58,7 @@ export const useFeaturePreviews = (): FeaturePreview[] => {key: LOCAL_STORAGE_KEYS.UI_PREVIEW_PG_DELTA_DIFF,name: 'PG Delta Diff',discussionsUrl: undefined,- isNew: true,+ isNew: false,isPlatformOnly: true,isDefaultOptIn: true,enabled: pgDeltaDiffEnabled,diff --git a/apps/studio/components/interfaces/Auth/RLSTester/InferredSQLViewer.tsx b/apps/studio/components/interfaces/Auth/RLSTester/InferredSQLViewer.tsxnew file mode 100644index 00000000000..f00876c50b3--- /dev/null+++ b/apps/studio/components/interfaces/Auth/RLSTester/InferredSQLViewer.tsx@@ -0,0 +1,25 @@+import { Badge, Tooltip, TooltipContent, TooltipTrigger } from 'ui'++import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'++export const InferredSQLViewer = ({ sql }: { sql: string }) => {+ return (+ <>+ <div className="flex items-center justify-between px-4 py-2">+ <p className="text-sm">Inferred SQL:</p>+ <Tooltip>+ <TooltipTrigger>+ <Badge variant="warning">Generated</Badge>+ </TooltipTrigger>+ <TooltipContent side="bottom" align="end" className="w-64 text-center">+ This query is inferred from client library code with the help of the Assistant and may+ not guarantee correctness.+ </TooltipContent>+ </Tooltip>+ </div>+ <div className="h-44 relative">+ <CodeEditor isReadOnly id="inferred-sql" language="pgsql" value={sql} />+ </div>+ </>+ )+}diff --git a/apps/studio/components/interfaces/Auth/RLSTester/RLSTableCard.tsx b/apps/studio/components/interfaces/Auth/RLSTester/RLSTableCard.tsxnew file mode 100644index 00000000000..d2753ab8bfe--- /dev/null+++ b/apps/studio/components/interfaces/Auth/RLSTester/RLSTableCard.tsx@@ -0,0 +1,192 @@+import { type PostgresPolicy } from '@supabase/postgres-meta'+import { Check, ChevronDown, Edit, X } from 'lucide-react'+import { useMemo } from 'react'+import {+ cn,+ Collapsible_Shadcn_,+ CollapsibleContent_Shadcn_,+ CollapsibleTrigger_Shadcn_,+ WarningIcon,+} from 'ui'++import { ButtonTooltip } from '@/components/ui/ButtonTooltip'++interface RLSTableCardProps {+ table: { schema: string; name: string; isRLSEnabled: boolean }+ role?: string+ policies: PostgresPolicy[]+ handleSelectEditPolicy: (policy: PostgresPolicy) => void+}++export const RLSTableCard = ({+ table,+ role,+ policies,+ handleSelectEditPolicy,+}: RLSTableCardProps) => {+ const { schema, name, isRLSEnabled } = table+ const trueOnlyPolicy = policies.find((x) => x.definition === 'true')+ const falseOnlyPolicy = policies.find((x) => x.definition === 'false')+ const noPolicies = isRLSEnabled && policies.length === 0++ const tableAccessDescription = useMemo(() => {+ if (!isRLSEnabled) {+ return (+ <p>+ RLS is disabled and all data is publicly accessible. We highly recommend enabling RLS and+ adding policies to restrict access.+ </p>+ )+ }++ if (noPolicies) {+ return (+ <p>+ RLS is enabled but no policies exist for the{' '}+ <code className="text-code-inline">{role}</code> role on this table - no data will be+ returned.+ </p>+ )+ }++ if (trueOnlyPolicy) {+ return (+ <>+ <p>+ The policy "{trueOnlyPolicy.name}" for the{' '}+ <code className="text-code-inline">{role}</code> role on this table evaluates to{' '}+ <code className="text-code-inline">true</code>, so all data from this query is+ accessible to this user.+ </p>+ <TableAccessPolicySummary+ policies={policies}+ handleSelectEditPolicy={handleSelectEditPolicy}+ />+ </>+ )+ }++ if (falseOnlyPolicy) {+ return (+ <>+ <p>+ The policy "{falseOnlyPolicy.name}" for the{' '}+ <code className="text-code-inline">{role}</code> role on this table evaluates to{' '}+ <code className="text-code-inline">false</code>, so no data from this query is+ accessible to this user.+ </p>+ <TableAccessPolicySummary+ policies={policies}+ handleSelectEditPolicy={handleSelectEditPolicy}+ />+ </>+ )+ }++ return (+ <>+ <p>+ {policies.length} {policies.length > 1 ? 'policies apply' : 'policy applies'} for the{' '}+ <code className="text-code-inline">{role}</code> role on this table. Only rows that match{' '}+ {policies.length > 1 ? 'these conditions' : 'this condition'} are returned.+ </p>+ <TableAccessPolicySummary+ policies={policies}+ handleSelectEditPolicy={handleSelectEditPolicy}+ />+ </>+ )+ }, [+ isRLSEnabled,+ noPolicies,+ trueOnlyPolicy,+ falseOnlyPolicy,+ policies,+ role,+ handleSelectEditPolicy,+ ])++ return (+ <Collapsible_Shadcn_+ className={cn('border rounded', !isRLSEnabled && 'bg-warning-300 border-warning-500')}+ >+ <CollapsibleTrigger_Shadcn_ className="flex items-center justify-between px-3 py-2 w-full [&[data-state=open]>div>svg]:!-rotate-180">+ <div className="w-full flex items-center justify-between">+ <div className="flex items-center gap-x-2">+ {!isRLSEnabled ? (+ <WarningIcon />+ ) : noPolicies || falseOnlyPolicy ? (+ <X size={16} className="text-destructive" />+ ) : (+ <Check size={16} className="text-brand" />+ )}+ <p className={cn('text-xs font-mono', !isRLSEnabled && 'font-medium text-foreground')}>+ {schema}.{name}+ </p>+ </div>+ </div>+ <div className="flex items-center gap-x-2">+ <p+ className={cn(+ 'text-xs text-foreground-light w-max',+ !isRLSEnabled && 'text-foreground'+ )}+ >+ {noPolicies || falseOnlyPolicy+ ? 'Returns no rows'+ : !isRLSEnabled || !!trueOnlyPolicy+ ? 'Returns all rows'+ : null}+ </p>+ <ChevronDown className="transition-transform duration-200" strokeWidth={1.5} size={14} />+ </div>+ </CollapsibleTrigger_Shadcn_>+ <CollapsibleContent_Shadcn_+ className={cn(+ 'border-t p-3 text-sm text-foreground-light',+ !isRLSEnabled && 'border-warning-500'+ )}+ >+ {tableAccessDescription}+ </CollapsibleContent_Shadcn_>+ </Collapsible_Shadcn_>+ )+}++const TableAccessPolicySummary = ({+ policies,+ handleSelectEditPolicy,+}: {+ policies: PostgresPolicy[]+ handleSelectEditPolicy: (policy: PostgresPolicy) => void+}) => {+ return (+ <div className="border rounded mt-4">+ <p className="text-xs font-mono text-foreground-light uppercase border-b px-3 py-2">+ {policies.length} {policies.length > 1 ? 'policies' : 'policy'} applied+ </p>+ <ul>+ {policies.map((policy) => (+ <li key={policy.id} className="px-3 py-2 flex justify-between items-center">+ <div>+ <p>{policy.name}</p>+ <p className="text-foreground-lighter">+ Show rows where:{' '}+ <code className="text-code-inline text-foreground">{policy.definition}</code>+ </p>+ </div>+ <ButtonTooltip+ type="text"+ icon={<Edit />}+ className="w-7"+ tooltip={{ content: { side: 'bottom', text: 'Edit policy' } }}+ onClick={() => {+ handleSelectEditPolicy(policy)+ }}+ />+ </li>+ ))}+ </ul>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Auth/RLSTester/RLSTester.types.ts b/apps/studio/components/interfaces/Auth/RLSTester/RLSTester.types.tsnew file mode 100644index 00000000000..5348663c0e5--- /dev/null+++ b/apps/studio/components/interfaces/Auth/RLSTester/RLSTester.types.ts@@ -0,0 +1,16 @@+import { type PostgresPolicy } from '@supabase/postgres-meta'++import { type User } from '@/data/auth/users-infinite-query'+import { type ParseSQLQueryResponse } from '@/data/misc/parse-query-mutation'++export type ParseQueryResults = {+ tables: {+ schema: string+ table: string+ tablePolicies: PostgresPolicy[]+ isRLSEnabled: boolean+ }[]+ operation: ParseSQLQueryResponse['operation']+ role?: string+ user?: User+}diff --git a/apps/studio/components/interfaces/Auth/RLSTester/RLSTesterEmptyState.tsx b/apps/studio/components/interfaces/Auth/RLSTester/RLSTesterEmptyState.tsxnew file mode 100644index 00000000000..d6eecd60beb--- /dev/null+++ b/apps/studio/components/interfaces/Auth/RLSTester/RLSTesterEmptyState.tsx@@ -0,0 +1,13 @@+import { ListTodo } from 'lucide-react'++export const RLSTesterEmptyState = () => {+ return (+ <div className="flex flex-col items-center justify-center h-64">+ <ListTodo className="mb-2 text-foreground-light" />+ <p className="text-foreground-light text-sm">Test summary and results will be shown here</p>+ <p className="text-foreground-lighter text-sm">+ Verify that the results match what your RLS policies allow+ </p>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Auth/RLSTester/RLSTesterResults.tsx b/apps/studio/components/interfaces/Auth/RLSTester/RLSTesterResults.tsxnew file mode 100644index 00000000000..a65ccedc7cb--- /dev/null+++ b/apps/studio/components/interfaces/Auth/RLSTester/RLSTesterResults.tsx@@ -0,0 +1,169 @@+import { type PostgresPolicy } from '@supabase/postgres-meta'+import {+ Badge,+ cn,+ Tabs_Shadcn_,+ TabsContent_Shadcn_,+ TabsList_Shadcn_,+ TabsTrigger_Shadcn_,+} from 'ui'+import { Admonition } from 'ui-patterns'++import { Results } from '../../SQLEditor/UtilityPanel/Results'+import { RLSTableCard } from './RLSTableCard'+import { ParseQueryResults } from './RLSTester.types'+import { useTestQueryRLS } from './useTestQueryRLS'++interface RLSTesterResultsProps {+ results: Object[]+ autoLimit: boolean+ parseQueryResults: ParseQueryResults+ handleSelectEditPolicy: (policy: PostgresPolicy) => void+}++export const RLSTesterResults = ({+ results,+ autoLimit,+ parseQueryResults,+ handleSelectEditPolicy,+}: RLSTesterResultsProps) => {+ const { limit } = useTestQueryRLS()++ const isServiceRole = parseQueryResults?.role === undefined+ const tableWithRLSEnabledButNoPolicies = parseQueryResults?.tables.find(+ (x) => x.isRLSEnabled && x.tablePolicies.length === 0+ )+ const tableWithRLSEnabledWithPolicyFalse = parseQueryResults?.tables.find(+ (x) => x.isRLSEnabled && x.tablePolicies.some((y) => y.definition === 'false')+ )++ const noAccessToData =+ !isServiceRole && (!!tableWithRLSEnabledButNoPolicies || !!tableWithRLSEnabledWithPolicyFalse)++ return (+ <div className="p-5 pt-4">+ <div className="flex items-center gap-x-2 mb-2">+ <p className="text-sm">Summary</p>+ {noAccessToData ? (+ <Badge variant="destructive">No access</Badge>+ ) : (+ <Badge variant="success">{results.length > 0 ? 'Can access' : 'Has access'}</Badge>+ )}+ </div>++ <Tabs_Shadcn_ defaultValue="policies">+ <TabsList_Shadcn_ className="gap-x-3">+ <TabsTrigger_Shadcn_ value="policies" className="px-2">+ Policies applied+ </TabsTrigger_Shadcn_>+ <TabsTrigger_Shadcn_ value="data" className="px-2">+ Data preview+ </TabsTrigger_Shadcn_>+ </TabsList_Shadcn_>++ {!!parseQueryResults && (+ <div className="border rounded flex items-center justify-between px-3 py-1.5 mt-3">+ <div className="flex items-center gap-x-2">+ <p className="text-xs text-foreground-light">Ran as</p>+ {!parseQueryResults.role ? (+ <code className="text-code-inline">postgres</code>+ ) : parseQueryResults.user ? (+ <p className="text-sm truncate max-w-52">{parseQueryResults.user.email}</p>+ ) : parseQueryResults.role === 'anon' ? (+ <p className="text-xs">an Anonymous user</p>+ ) : null}+ </div>++ {parseQueryResults.role === 'anon' && (+ <p className="text-foreground-light text-xs">Not logged in user</p>+ )}+ {!!parseQueryResults.user && (+ <code className="text-code-inline">ID: {parseQueryResults.user.id}</code>+ )}+ </div>+ )}++ <TabsContent_Shadcn_ value="policies" className="mt-0">+ {!isServiceRole && !!tableWithRLSEnabledButNoPolicies && (+ <Admonition showIcon={false} type="default" className="rounded mt-2">+ <p className="!mb-0.5">This user has no access to any rows from this query</p>+ <p className="text-foreground-light">+ The table{' '}+ <code className="text-code-inline">+ {tableWithRLSEnabledButNoPolicies.schema}.{tableWithRLSEnabledButNoPolicies.table}+ </code>{' '}+ has RLS enabled but no policies set up for the{' '}+ <code className="text-code-inline !break-keep">{parseQueryResults.role}</code> role.+ </p>+ </Admonition>+ )}++ {!isServiceRole && tableWithRLSEnabledWithPolicyFalse && (+ <Admonition showIcon={false} type="default" className="rounded mt-2">+ <p className="!mb-0.5">This user has no access to any rows from this query</p>+ <p className="text-foreground-light">+ The table{' '}+ <code className="text-code-inline">+ {tableWithRLSEnabledWithPolicyFalse.schema}.+ {tableWithRLSEnabledWithPolicyFalse.table}+ </code>{' '}+ has a policy that evaluates to+ <code className="text-code-inline !break-keep">false</code> for the{' '}+ <code className="text-code-inline !break-keep">{parseQueryResults.role}</code> role.+ </p>+ </Admonition>+ )}++ {isServiceRole && (+ <Admonition showIcon={false} type="default" className="rounded mt-2">+ <p className="!mb-0.5">+ The <code className="text-code-inline">postgres</code> role has access to all rows+ for this query+ </p>+ <p className="text-foreground-light">+ The <code className="text-code-inline">postgres</code> role has admin privileges and+ bypasses all RLS policies.+ </p>+ </Admonition>+ )}++ <div className="flex flex-col gap-y-2 mt-4">+ <p className="text-sm">Table access</p>+ {!isServiceRole && (+ <div className="flex flex-col gap-y-2">+ {parseQueryResults?.tables.map((x) => {+ const { schema, table, tablePolicies, isRLSEnabled } = x+ return (+ <RLSTableCard+ key={`${schema}.${table}`}+ table={{ schema, name: table, isRLSEnabled }}+ role={parseQueryResults.role}+ policies={tablePolicies}+ handleSelectEditPolicy={handleSelectEditPolicy}+ />+ )+ })}+ </div>+ )}+ </div>+ </TabsContent_Shadcn_>+ <TabsContent_Shadcn_ value="data" className="mt-2">+ <div+ className={cn(+ 'flex-grow flex flex-col border overflow-hidden',+ results.length === 0 ? 'rounded h-32' : 'rounded-t h-56'+ )}+ >+ <Results rows={results} />+ </div>+ {results.length > 0 && (+ <p className="border border-t-0 rounded-b font-mono text-xs text-foreground-light p-2">+ {results.length} row{results.length > 1 ? 's' : ''}+ {autoLimit && results.length >= limit && ` (Limited to only ${limit} rows)`}+ </p>+ )}+ </TabsContent_Shadcn_>+ </Tabs_Shadcn_>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Auth/RLSTester/RLSTesterSheet.tsx b/apps/studio/components/interfaces/Auth/RLSTester/RLSTesterSheet.tsxnew file mode 100644index 00000000000..8d9918fba52--- /dev/null+++ b/apps/studio/components/interfaces/Auth/RLSTester/RLSTesterSheet.tsx@@ -0,0 +1,208 @@+import { type PostgresPolicy } from '@supabase/postgres-meta'+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectLabel,+ SelectTrigger,+ SelectValue,+} from '@ui/components/shadcn/ui/select'+import { Code } from 'lucide-react'+import { useEffect, useState } from 'react'+import {+ Button,+ DialogSectionSeparator,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetSection,+ SheetTitle,+ SheetTrigger,+} from 'ui'+import { Admonition } from 'ui-patterns'++import { InferredSQLViewer } from './InferredSQLViewer'+import { type ParseQueryResults } from './RLSTester.types'+import { RLSTesterEmptyState } from './RLSTesterEmptyState'+import { RLSTesterResults } from './RLSTesterResults'+import { RoleSelector } from './RoleSelector'+import { UserSelector } from './UserSelector'+import { useTestQueryRLS } from './useTestQueryRLS'+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'+import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'++interface RLSTesterSheetProps {+ handleSelectEditPolicy: (policy: PostgresPolicy) => void+}++export const RLSTesterSheet = ({ handleSelectEditPolicy }: RLSTesterSheetProps) => {+ const { setRole } = useRoleImpersonationStateSnapshot()++ const [open, setOpen] = useState(false)+ const [selectedOption, setSelectedOption] = useState<'anon' | 'authenticated'>('anon')++ const [format, setFormat] = useState<'sql' | 'lib'>('sql')+ const [inferredSQL, setInferredSQL] = useState<string>()++ const [value, setValue] = useState<string>('')+ const [results, setResults] = useState<Object[] | null>(null)+ const [autoLimit, setAutoLimit] = useState(false)+ const [parseQueryResults, setParseQueryResults] = useState<ParseQueryResults>()++ const { testQuery, isLoading, executeSqlError, parseQueryError, parseClientCodeError } =+ useTestQueryRLS()++ const onRunQuery = async () => {+ await testQuery({+ option: selectedOption,+ format,+ value,+ onInferSQL: setInferredSQL,+ onParseQuery: setParseQueryResults,+ onExecuteSQL: ({ result, isAutoLimit }) => {+ setResults(result)+ setAutoLimit(isAutoLimit)+ },+ })+ }++ useEffect(() => {+ setRole({ type: 'postgrest', role: 'anon' })+ // Flip back to service role+ return () => {+ setRole(undefined)+ }+ }, [setRole])++ return (+ <Sheet open={open} onOpenChange={setOpen}>+ <SheetTrigger asChild>+ <Button type="default" icon={<Code />}>+ Test+ </Button>+ </SheetTrigger>++ <SheetContent className="!w-[600px] flex flex-col gap-y-0">+ <SheetHeader>+ <SheetTitle>What data can my users see?</SheetTitle>+ <SheetDescription>+ See what data a user is allowed to read based on your RLS policies+ </SheetDescription>+ </SheetHeader>++ <div className="flex-grow overflow-y-auto flex flex-col">+ <SheetSection className="px-0 py-0">+ <div className="flex flex-col p-5 pt-4 gap-y-4">+ <RoleSelector onSelectRole={setSelectedOption} />+ {selectedOption === 'authenticated' && <UserSelector />}+ </div>++ <DialogSectionSeparator />++ <div className="flex items-center justify-between px-5 py-2">+ <p className="text-sm">Query</p>+ <div className="flex items-center gap-x-2">+ <Select value={format} onValueChange={(x) => setFormat(x as 'sql' | 'lib')}>+ <SelectTrigger size="tiny">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ <SelectLabel>Query format</SelectLabel>+ <SelectItem value="sql">SQL</SelectItem>+ <SelectItem value="lib">Client library</SelectItem>+ </SelectGroup>+ </SelectContent>+ </Select>+ </div>+ </div>++ <div className="h-40 relative">+ <CodeEditor+ id="rls-tester"+ language="pgsql"+ value={value}+ placeholder={+ format === 'sql'+ ? 'select * from table;'+ : 'SQL will be inferred from client library code'+ }+ onInputChange={(val) => setValue(val ?? '')}+ actions={{+ runQuery: {+ enabled: open,+ callback: () => {+ if (!isLoading) onRunQuery()+ },+ },+ }}+ />+ </div>+ </SheetSection>++ {format === 'lib' && !!inferredSQL && (+ <div>+ <DialogSectionSeparator />+ <InferredSQLViewer sql={inferredSQL} />+ </div>+ )}++ <DialogSectionSeparator />++ {parseQueryError && (+ <div className="p-4">+ <Admonition+ type="warning"+ title="Error parsing query"+ description={parseQueryError.message}+ />+ </div>+ )}++ {parseClientCodeError && (+ <div className="p-4">+ <Admonition+ type="warning"+ title="Error parsing client code"+ description={parseClientCodeError.message}+ />+ </div>+ )}++ {executeSqlError && (+ <div className="p-4">+ <Admonition+ type="warning"+ title="Error running SQL query"+ description={executeSqlError.message}+ />+ </div>+ )}++ {results === null ? (+ <RLSTesterEmptyState />+ ) : !!parseQueryResults ? (+ <RLSTesterResults+ results={results}+ parseQueryResults={parseQueryResults}+ autoLimit={autoLimit}+ handleSelectEditPolicy={handleSelectEditPolicy}+ />+ ) : null}+ </div>++ <SheetFooter>+ <Button type="default" disabled={isLoading} onClick={() => setOpen(false)}>+ Cancel+ </Button>+ <Button type="primary" loading={isLoading} onClick={onRunQuery}>+ Run query+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>+ )+}diff --git a/apps/studio/components/interfaces/Auth/RLSTester/RoleSelector.tsx b/apps/studio/components/interfaces/Auth/RLSTester/RoleSelector.tsxnew file mode 100644index 00000000000..b25aab9d137--- /dev/null+++ b/apps/studio/components/interfaces/Auth/RLSTester/RoleSelector.tsx@@ -0,0 +1,38 @@+import { RadioGroupStacked, RadioGroupStackedItem } from 'ui'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'++import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'++interface RoleSelectorProps {+ onSelectRole: (value: 'anon' | 'authenticated') => void+}++export const RoleSelector = ({ onSelectRole }: RoleSelectorProps) => {+ const { role, setRole } = useRoleImpersonationStateSnapshot()++ return (+ <FormItemLayout isReactForm={false} label="Test as">+ <RadioGroupStacked defaultValue={role?.role ?? 'anon'}>+ <RadioGroupStackedItem+ value="anon"+ id="anon"+ label="Anonymous user"+ description="Not logged in"+ onClick={() => {+ onSelectRole('anon')+ setRole({ type: 'postgrest', role: 'anon' })+ }}+ />+ <RadioGroupStackedItem+ value="authenticated"+ id="authenticated"+ label="Authenticated user"+ description="A specific logged in user"+ onClick={() => {+ onSelectRole('authenticated')+ }}+ />+ </RadioGroupStacked>+ </FormItemLayout>+ )+}diff --git a/apps/studio/components/interfaces/Auth/RLSTester/UserSelector.tsx b/apps/studio/components/interfaces/Auth/RLSTester/UserSelector.tsxnew file mode 100644index 00000000000..f92c9d91823--- /dev/null+++ b/apps/studio/components/interfaces/Auth/RLSTester/UserSelector.tsx@@ -0,0 +1,144 @@+import { keepPreviousData } from '@tanstack/react-query'+import { useDebounce } from '@uidotdev/usehooks'+import { Check, ChevronsUpDown } from 'lucide-react'+import { useMemo, useState } from 'react'+import { toast } from 'sonner'+import {+ Button,+ cn,+ Command_Shadcn_,+ CommandEmpty_Shadcn_,+ CommandGroup_Shadcn_,+ CommandInput_Shadcn_,+ CommandItem_Shadcn_,+ CommandList_Shadcn_,+ Popover_Shadcn_,+ PopoverContent_Shadcn_,+ PopoverTrigger_Shadcn_,+ ScrollArea,+} from 'ui'+import { Admonition, GenericSkeletonLoader } from 'ui-patterns'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'++import { User, useUsersInfiniteQuery } from '@/data/auth/users-infinite-query'+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'+import { ResponseError } from '@/types'++export const UserSelector = () => {+ const { data: project } = useSelectedProjectQuery()+ const state = useRoleImpersonationStateSnapshot()++ const [open, setOpen] = useState(false)+ const [searchText, setSearchText] = useState('')++ const debouncedSearchText = useDebounce(searchText, 300)++ const { data, error, isSuccess, isPending, isError } = useUsersInfiniteQuery(+ {+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ keywords: debouncedSearchText.trim().toLocaleLowerCase(),+ },+ { placeholderData: keepPreviousData }+ )+ const users = useMemo(() => data?.pages.flatMap((page) => page.result) ?? [], [data?.pages])++ const impersonatingUser =+ state.role?.type === 'postgrest' &&+ state.role.role === 'authenticated' &&+ state.role.userType === 'native'+ ? state.role.user+ : undefined++ const onSelectUser = async (user: User) => {+ try {+ await state.setRole({+ type: 'postgrest',+ role: 'authenticated',+ userType: 'native',+ user,+ aal: 'aal1',+ })+ } catch (error) {+ toast.error(`Failed to impersonate user: ${(error as ResponseError).message}`)+ }+ }++ return (+ <FormItemLayout isReactForm={false} label="Select which user to test as">+ <Popover_Shadcn_ open={open} onOpenChange={setOpen} modal>+ <PopoverTrigger_Shadcn_ asChild>+ <Button+ block+ type="default"+ role="combobox"+ size="small"+ aria-expanded={open}+ className={cn('justify-between', !impersonatingUser && 'text-foreground-lighter')}+ iconRight={<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />}+ >+ {impersonatingUser?.email ?? 'Select a user'}+ </Button>+ </PopoverTrigger_Shadcn_>+ <PopoverContent_Shadcn_ sameWidthAsTrigger className="p-0" side="bottom" align="start">+ <Command_Shadcn_ shouldFilter={false}>+ <CommandInput_Shadcn_+ showResetIcon+ placeholder="Search for a user"+ className="text-xs"+ value={searchText}+ onValueChange={setSearchText}+ />++ <CommandEmpty_Shadcn_>No user found</CommandEmpty_Shadcn_>++ {isError && (+ <Admonition showIcon={false} type="warning" className="border-0 rounded-none text-xs">+ Failed to fetch users: {error.message}+ </Admonition>+ )}++ <CommandList_Shadcn_>+ {isPending && (+ <div className="p-2">+ <GenericSkeletonLoader />+ </div>+ )}++ {isSuccess && (+ <CommandGroup_Shadcn_>+ <ScrollArea className={users.length > 7 ? 'h-full md:h-[210px]' : ''}>+ {users.map((user) => {+ return (+ <CommandItem_Shadcn_+ key={user.id}+ value={user.email}+ className="cursor-pointer w-full"+ onSelect={() => {+ onSelectUser(user)+ setOpen(false)+ }}+ >+ <div className="w-full flex items-center justify-between">+ <p className="space-x-3">+ <span className="text-foreground-light">{user.email}</span>+ <code className="text-code-inline !text-foreground-lighter">+ {user.id?.slice(0, 8)}+ </code>+ </p>+ {impersonatingUser?.id === user.id && <Check size={16} />}+ </div>+ </CommandItem_Shadcn_>+ )+ })}+ </ScrollArea>+ </CommandGroup_Shadcn_>+ )}+ </CommandList_Shadcn_>+ </Command_Shadcn_>+ </PopoverContent_Shadcn_>+ </Popover_Shadcn_>+ </FormItemLayout>+ )+}diff --git a/apps/studio/components/interfaces/Auth/RLSTester/useTestQueryRLS.ts b/apps/studio/components/interfaces/Auth/RLSTester/useTestQueryRLS.tsnew file mode 100644index 00000000000..e90163582f2--- /dev/null+++ b/apps/studio/components/interfaces/Auth/RLSTester/useTestQueryRLS.ts@@ -0,0 +1,184 @@+import { useState } from 'react'+import { toast } from 'sonner'++import { checkIfAppendLimitRequired, suffixWithLimit } from '../../SQLEditor/SQLEditor.utils'+import { type ParseQueryResults } from './RLSTester.types'+import { useParseClientCodeMutation } from '@/data/ai/parse-client-code-mutation'+import { useDatabasePoliciesQuery } from '@/data/database-policies/database-policies-query'+import { useCheckTableRLSStatusMutation } from '@/data/database/table-check-rls-mutation'+import { useParseSQLQueryMutation } from '@/data/misc/parse-query-mutation'+import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+import { wrapWithRoleImpersonation } from '@/lib/role-impersonation'+import {+ getImpersonatedUser,+ isRoleImpersonationEnabled,+ useGetImpersonatedRoleState,+ useRoleImpersonationStateSnapshot,+} from '@/state/role-impersonation-state'++const limit = 100++/**+ * [Joshen] Testing a SQL query for it's RLS access involves 3 async steps+ * 0. (Optional) Inferring client library code to SQL query via the AI Assistant+ * 1. Parsing the provided SQL query to retrieve its operation type + tables involved+ * 2. Checking for tables involved if they've got RLS enabled+ * 3. Actually running the query to retrieve the results+ *+ * Errors should all be handled as part of the UI instead of toasts, hence the empty onError+ * handlers to mute the default error handlers within the react query mutationhooks+ */+export const useTestQueryRLS = () => {+ const { data: project } = useSelectedProjectQuery()+ const { role } = useRoleImpersonationStateSnapshot()++ const getImpersonatedRoleState = useGetImpersonatedRoleState()+ const impersonatedRoleState = getImpersonatedRoleState()++ const [isLoading, setIsLoading] = useState(false)++ const { data: policies = [] } = useDatabasePoliciesQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })++ const { mutateAsync: executeSql, error: executeSqlError } = useExecuteSqlMutation({+ onError: () => {},+ })++ const { mutateAsync: parseClientCode, error: parseClientCodeError } = useParseClientCodeMutation({+ onError: () => {},+ })++ const { mutateAsync: parseQuery, error: parseQueryError } = useParseSQLQueryMutation({+ onError: () => {},+ })++ const { mutateAsync: getTableRLSStatus, error: getTableRLSStatusError } =+ useCheckTableRLSStatusMutation({+ onError: () => {},+ })++ const testQuery = async ({+ option,+ format,+ value,+ onInferSQL,+ onExecuteSQL,+ onParseQuery,+ }: {+ option: 'anon' | 'authenticated'+ format: 'lib' | 'sql'+ value: string+ onInferSQL: (sql: string) => void+ onExecuteSQL: ({+ result,+ isAutoLimit,+ }: {+ result: Object[] | null+ isAutoLimit: boolean+ }) => void+ onParseQuery: (results?: ParseQueryResults) => void+ }) => {+ if (!project) return console.error('Project is required')+ const user = getImpersonatedUser(impersonatedRoleState)++ if (option === 'authenticated' && !user) {+ return toast('Select which user to test as before running the query')+ }++ try {+ setIsLoading(true)+ let formattedValue = value++ if (format === 'lib') {+ const { sql, valid } = await parseClientCode({ code: value })+ if (valid && !!sql) {+ formattedValue = sql+ onInferSQL(sql)+ } else {+ return toast.error('Client library code provided is not valid')+ }+ }++ const { appendAutoLimit } = checkIfAppendLimitRequired(formattedValue, limit)+ const formattedSql = suffixWithLimit(formattedValue, limit)+ const data = await parseQuery({ sql: formattedSql })++ if (data.operation !== 'SELECT') {+ return toast('Only SELECT statements are supported for now')+ }++ const formattedTables = data.tables.map((x) => {+ const [schema, table] = x.includes('.') ? x.split('.') : ['public', x]+ return { schema, table }+ })+ const response = await getTableRLSStatus({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ tables: formattedTables,+ })++ const tables = response+ .map(({ table, schema, rls_enabled }) => {+ const tablePolicies = policies.filter(+ (x) =>+ x.schema === schema &&+ x.table === table &&+ x.roles.includes(role?.role ?? '') &&+ x.command === data.operation+ )+ return {+ table,+ schema,+ isRLSEnabled: rls_enabled,+ tablePolicies,+ }+ })+ .sort((a, b) => {+ const aFirst = a.isRLSEnabled && a.tablePolicies.length === 0+ const bFirst = b.isRLSEnabled && b.tablePolicies.length === 0+ return Number(bFirst) - Number(aFirst)+ })++ const autoLimit = appendAutoLimit ? limit : undefined+ const { result } = await executeSql({+ autoLimit,+ projectRef: project.ref,+ connectionString: project.connectionString,+ sql: wrapWithRoleImpersonation(formattedSql, impersonatedRoleState),+ isRoleImpersonationEnabled: isRoleImpersonationEnabled(impersonatedRoleState.role),+ isStatementTimeoutDisabled: true,+ handleError: (error) => {+ throw error+ },+ queryKey: ['rls-tester'],+ })++ onExecuteSQL({ result, isAutoLimit: !!autoLimit })++ onParseQuery({+ tables,+ operation: data.operation,+ role: role?.role,+ user,+ })+ } catch (error) {+ onExecuteSQL({ result: null, isAutoLimit: false })+ onParseQuery(undefined)+ } finally {+ setIsLoading(false)+ }+ }++ return {+ limit,+ testQuery,+ isLoading,+ executeSqlError,+ parseQueryError,+ parseClientCodeError,+ getTableRLSStatusError,+ }+}diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsxindex 49a9afaac34..a4337904c4a 100644--- a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx@@ -9,7 +9,7 @@ export interface RoleImpersonationRadioProps<T extends string> {icon?: React.ReactNode}-function RoleImpersonationRadio<T extends string>({+export function RoleImpersonationRadio<T extends string>({label,value,isSelected,@@ -67,5 +67,3 @@ function RoleImpersonationRadio<T extends string>({</label>)}--export default RoleImpersonationRadiodiff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsxindex 316eda7f88d..badaa40dedd 100644--- a/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx@@ -34,7 +34,7 @@ import type { ResponseError } from '@/types'type AuthenticatorAssuranceLevels = 'aal1' | 'aal2'-const UserImpersonationSelector = () => {+export const UserImpersonationSelector = () => {const [searchText, setSearchText] = useState('')const [aal, setAal] = useState<AuthenticatorAssuranceLevels>('aal1')const [externalUserId, setExternalUserId] = useState('')@@ -421,8 +421,6 @@ const UserImpersonationSelector = () => {)}-export default UserImpersonationSelector-// Base interface for shared impersonation row props to reduce// duplication between user and external auth impersonation displaysinterface BaseImpersonatingRowProps {@@ -462,7 +460,7 @@ const BaseImpersonatingRow = ({</div><Button type="default" onClick={onClick} disabled={isLoading} loading={isLoading}>- {isImpersonating ? 'Stop Impersonating' : 'Impersonate'}+ {isImpersonating ? 'Stop impersonating' : 'Impersonate'}</Button></div>)@@ -558,7 +556,7 @@ const UserRow = ({ user, onClick, isImpersonating = false, isLoading = false }:</div><Button type="default" onClick={() => onClick(user)} disabled={isLoading} loading={isLoading}>- {isImpersonating ? 'Stop Impersonating' : 'Impersonate'}+ {isImpersonating ? 'Stop impersonating' : 'Impersonate'}</Button></div>)diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsxindex e818dd6f18a..7a9544119df 100644--- a/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx@@ -2,8 +2,8 @@ import { useState } from 'react'import { cn, DropdownMenuSeparator } from 'ui'import { AnonIcon, AuthenticatedIcon, ServiceRoleIcon } from './Icons'-import RoleImpersonationRadio from './RoleImpersonationRadio'-import UserImpersonationSelector from './UserImpersonationSelector'+import { RoleImpersonationRadio } from './RoleImpersonationRadio'+import { UserImpersonationSelector } from './UserImpersonationSelector'import { PostgrestRole } from '@/lib/role-impersonation'import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'@@ -11,6 +11,7 @@ export interface RoleImpersonationSelectorProps {serviceRoleLabel?: stringpadded?: booleandisallowAuthenticatedOption?: boolean+ title?: string}export const RoleImpersonationSelector = ({diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsxindex fc511317cf2..c137c36de79 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx@@ -50,7 +50,7 @@ import {suffixWithLimit,} from './SQLEditor.utils'import { useAddDefinitions } from './useAddDefinitions'-import UtilityPanel from './UtilityPanel/UtilityPanel'+import { UtilityPanel } from './UtilityPanel/UtilityPanel'import {isExplainQuery,isExplainSql,diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsxindex 939e806f454..5a4e3f09ebc 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx@@ -14,7 +14,7 @@ import { CellDetailPanel } from './CellDetailPanel'import { formatCellValue, formatClipboardValue } from './Results.utils'import { handleCopyCell } from '@/components/grid/SupabaseGrid.utils'-const Results = ({ rows }: { rows: readonly any[] }) => {+export const Results = ({ rows }: { rows: readonly any[] }) => {const [expandCell, setExpandCell] = useState(false)const [cellPosition, setCellPosition] = useState<{ column: any; row: any; rowIdx: number }>()const contextMenuCellRef = useRef<{ column: string; value: any } | null>(null)diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsxindex 4545f7e033b..7c4fce807e2 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx@@ -32,7 +32,7 @@ export type UtilityActionsProps = {executeQuery: () => void}-const UtilityActions = ({+export const UtilityActions = ({id,isExecuting = false,isDisabled = false,@@ -211,5 +211,3 @@ const UtilityActions = ({</div>)}--export default UtilityActionsdiff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsxindex 4f52943f93e..03f1821e044 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx@@ -1,11 +1,11 @@-import { useFlag, useParams } from 'common'+import { useParams } from 'common'import { toast } from 'sonner'import { Tabs_Shadcn_, TabsContent_Shadcn_, TabsList_Shadcn_, TabsTrigger_Shadcn_ } from 'ui'import { ChartConfig } from './ChartConfig'-import UtilityActions from './UtilityActions'+import { UtilityActions } from './UtilityActions'import { UtilityTabExplain } from './UtilityTabExplain'-import UtilityTabResults from './UtilityTabResults'+import { UtilityTabResults } from './UtilityTabResults'import { DownloadResultsButton } from '@/components/ui/DownloadResultsButton'import { useContentUpsertMutation } from '@/data/content/content-upsert-mutation'import { Snippet } from '@/data/content/sql-folders-query'@@ -38,7 +38,7 @@ const DEFAULT_CHART_CONFIG: ChartConfig = {showGrid: false,}-const UtilityPanel = ({+export const UtilityPanel = ({id,isExecuting,isExplainExecuting,@@ -56,7 +56,6 @@ const UtilityPanel = ({const { ref } = useParams()const { data: org } = useSelectedOrganizationQuery()const snapV2 = useSqlEditorV2StateSnapshot()- const showPrettyExplain = useFlag('ShowPrettyExplain')const snippet = snapV2.snippets[id]?.snippetconst result = snapV2.results[id]?.[0]@@ -140,15 +139,13 @@ const UtilityPanel = ({<TabsTrigger_Shadcn_ className="py-3 text-xs" value="results"><span className="translate-y-[1px]">Results</span></TabsTrigger_Shadcn_>- {/* Only show Explain tab if ShowPrettyExplain flag is on */}- {showPrettyExplain && (- <TabsTrigger_Shadcn_ className="py-3 text-xs" value="explain">- <span className="translate-y-[1px]">Explain</span>- </TabsTrigger_Shadcn_>- )}+ <TabsTrigger_Shadcn_ className="py-3 text-xs" value="explain">+ <span className="translate-y-[1px]">Explain</span>+ </TabsTrigger_Shadcn_><TabsTrigger_Shadcn_ className="py-3 text-xs" value="chart"><span className="translate-y-[1px]">Chart</span></TabsTrigger_Shadcn_>+{result?.rows && (<DownloadResultsButtontype="text"@@ -181,6 +178,7 @@ const UtilityPanel = ({/>)}</div>+<UtilityActionsid={id}isExecuting={isExecuting}@@ -190,6 +188,7 @@ const UtilityPanel = ({executeQuery={executeQuery}/></TabsList_Shadcn_>+<TabsContent_Shadcn_ asChild value="results" className="mt-0 flex-grow"><UtilityTabResultsid={id}@@ -201,12 +200,9 @@ const UtilityPanel = ({/></TabsContent_Shadcn_>- {/* Only render Explain tab content if ShowPrettyExplain flag is on */}- {showPrettyExplain && (- <TabsContent_Shadcn_ asChild value="explain" className="mt-0 flex-grow">- <UtilityTabExplain id={id} isExecuting={isExplainExecuting} />- </TabsContent_Shadcn_>- )}+ <TabsContent_Shadcn_ asChild value="explain" className="mt-0 flex-grow">+ <UtilityTabExplain id={id} isExecuting={isExplainExecuting} />+ </TabsContent_Shadcn_><TabsContent_Shadcn_ asChild value="chart" className="mt-0 flex-grow"><ChartConfig results={result} config={chartConfig} onConfigChange={onConfigChange} />@@ -214,5 +210,3 @@ const UtilityPanel = ({</Tabs_Shadcn_>)}--export default UtilityPaneldiff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsxindex 4dd9ab97572..2ad0fef942b 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx@@ -26,7 +26,7 @@ export type UtilityTabResultsProps = {isDebugging?: boolean}-const UtilityTabResults = forwardRef<HTMLDivElement, UtilityTabResultsProps>(+export const UtilityTabResults = forwardRef<HTMLDivElement, UtilityTabResultsProps>(({ id, isExecuting, isDisabled, isDebugging, onDebug, buildDebugPrompt }) => {const { ref } = useParams()const state = useDatabaseSelectorStateSnapshot()@@ -173,7 +173,7 @@ const UtilityTabResults = forwardRef<HTMLDivElement, UtilityTabResultsProps>(return (<div className="bg-table-header-light [[data-theme*=dark]_&]:bg-table-header-dark overflow-y-auto"><p className="m-0 border-0 px-4 py-4 text-sm text-foreground-light">- Click <code>Run</code> to execute your query.+ Click <code className="text-code-inline">Run</code> to execute your query</p></div>)@@ -190,4 +190,3 @@ const UtilityTabResults = forwardRef<HTMLDivElement, UtilityTabResultsProps>()UtilityTabResults.displayName = 'UtilityTabResults'-export default UtilityTabResultsdiff --git a/apps/studio/components/ui/CodeEditor/CodeEditor.tsx b/apps/studio/components/ui/CodeEditor/CodeEditor.tsxindex 77fb646c56e..6f401ac87c2 100644--- a/apps/studio/components/ui/CodeEditor/CodeEditor.tsx+++ b/apps/studio/components/ui/CodeEditor/CodeEditor.tsx@@ -43,7 +43,7 @@ interface CodeEditorProps {onInputChange?: (value?: string) => void}-const CodeEditor = ({+export const CodeEditor = ({id,language,defaultValue,@@ -116,11 +116,7 @@ const CodeEditor = ({// @ts-ignoreidentifier: 'add-placeholder',range: new monaco.Range(1, 1, 1, 1),- text: (placeholder ?? '')- .split('\n\n')- .join('\n')- .replaceAll('*', '')- .replaceAll(' ', ' '),+ text: (placeholder ?? '').split('\n\n').join('\n').replaceAll(' ', ' '),},])},diff --git a/apps/studio/data/ai/parse-client-code-mutation.ts b/apps/studio/data/ai/parse-client-code-mutation.tsnew file mode 100644index 00000000000..801010a1ba8--- /dev/null+++ b/apps/studio/data/ai/parse-client-code-mutation.ts@@ -0,0 +1,58 @@+import { useMutation } from '@tanstack/react-query'+import { toast } from 'sonner'++import { constructHeaders, fetchHandler } from '@/data/fetchers'+import { BASE_PATH } from '@/lib/constants'+import { ResponseError, UseCustomMutationOptions } from '@/types'++export type ParseClientCodeResponse = {+ sql: string | undefined+ valid: boolean+}++export type ParseClientCodeVariables = {+ code: string+}++export async function generateSqlTitle({ code }: ParseClientCodeVariables) {+ try {+ const url = `${BASE_PATH}/api/ai/sql/parse-client-code`+ const headers = await constructHeaders({ 'Content-Type': 'application/json' })+ const response = await fetchHandler(url, {+ headers,+ method: 'POST',+ body: JSON.stringify({ code }),+ }).then((res) => res.json())++ if (response.error) throw new Error(response.error)+ return response as ParseClientCodeResponse+ } catch (error) {+ throw error+ }+}++type ParseClientCodeData = Awaited<ReturnType<typeof generateSqlTitle>>++export const useParseClientCodeMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<ParseClientCodeData, ResponseError, ParseClientCodeVariables>,+ 'mutationFn'+> = {}) => {+ return useMutation<ParseClientCodeData, ResponseError, ParseClientCodeVariables>({+ mutationFn: (vars) => generateSqlTitle(vars),+ async onSuccess(data, variables, context) {+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to parse client code: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/database/table-check-rls-mutation.ts b/apps/studio/data/database/table-check-rls-mutation.tsnew file mode 100644index 00000000000..039c1a9a431--- /dev/null+++ b/apps/studio/data/database/table-check-rls-mutation.ts@@ -0,0 +1,59 @@+import { getTablesRlsEnabledStatusSQL } from '@supabase/pg-meta'+import { useMutation } from '@tanstack/react-query'+import { toast } from 'sonner'++import { executeSql } from '../sql/execute-sql-query'+import { ResponseError, UseCustomMutationOptions } from '@/types'++type CheckTableRLSStatusVariables = {+ projectRef?: string+ connectionString?: string | null+ tables: { schema: string; table: string }[]+}++export type CheckTableRLSStatusResponse = {+ schema: string+ table: string+ rls_enabled: boolean+}++export async function checkTableRLSStatus({+ projectRef,+ connectionString,+ tables,+}: CheckTableRLSStatusVariables) {+ const sql = getTablesRlsEnabledStatusSQL({ tables })+ const { result } = await executeSql({+ projectRef,+ connectionString,+ sql,+ queryKey: ['table-rls-status'],+ })+ return result as CheckTableRLSStatusResponse[]+}++type CheckTableRLSStatusData = Awaited<ReturnType<typeof checkTableRLSStatus>>++export const useCheckTableRLSStatusMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<CheckTableRLSStatusData, ResponseError, CheckTableRLSStatusVariables>,+ 'mutationFn'+> = {}) => {+ return useMutation<CheckTableRLSStatusData, ResponseError, CheckTableRLSStatusVariables>({+ mutationFn: (vars) => checkTableRLSStatus(vars),+ async onSuccess(data, variables, context) {+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to retrieve table RLS statuses: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/misc/parse-query-mutation.ts b/apps/studio/data/misc/parse-query-mutation.tsnew file mode 100644index 00000000000..0a36df7bca5--- /dev/null+++ b/apps/studio/data/misc/parse-query-mutation.ts@@ -0,0 +1,56 @@+import { useMutation } from '@tanstack/react-query'+import { toast } from 'sonner'++import { constructHeaders, fetchHandler } from '@/data/fetchers'+import { BASE_PATH } from '@/lib/constants'+import { ResponseError, UseCustomMutationOptions } from '@/types'++type ParseSQLQueryVariables = { sql: string }+export type ParseSQLQueryResponse = {+ tables: string[]+ operation: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | undefined+}++export async function parseSQLQuery({ sql }: ParseSQLQueryVariables) {+ try {+ const url = `${BASE_PATH}/api/parse-query`++ const headers = await constructHeaders({ 'Content-Type': 'application/json' })+ const response = await fetchHandler(url, {+ headers,+ method: 'POST',+ body: JSON.stringify({ sql }),+ }).then((res) => res.json())++ if (response.error) throw new Error(response.error)+ return response as ParseSQLQueryResponse+ } catch (error) {+ throw error+ }+}++type ParseSQLQueryData = Awaited<ReturnType<typeof parseSQLQuery>>++export const useParseSQLQueryMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<ParseSQLQueryData, ResponseError, ParseSQLQueryVariables>,+ 'mutationFn'+> = {}) => {+ return useMutation<ParseSQLQueryData, ResponseError, ParseSQLQueryVariables>({+ mutationFn: (vars) => parseSQLQuery(vars),+ async onSuccess(data, variables, context) {+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to parse query: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/next.config.ts b/apps/studio/next.config.tsindex 2f3b59c76cf..de8e6c883f3 100644--- a/apps/studio/next.config.ts+++ b/apps/studio/next.config.ts@@ -599,15 +599,8 @@ const nextConfig = {: []),],},- transpilePackages: [- 'ui',- 'ui-patterns',- 'common',- 'shared-data',- 'api-types',- 'icons',- 'libpg-query',- ],+ transpilePackages: ['ui', 'ui-patterns', 'common', 'shared-data', 'api-types', 'icons'],+ serverExternalPackages: ['libpg-query'],turbopack: {rules: {'*.md': {diff --git a/apps/studio/pages/api/ai/sql/parse-client-code.ts b/apps/studio/pages/api/ai/sql/parse-client-code.tsnew file mode 100644index 00000000000..546eb716f36--- /dev/null+++ b/apps/studio/pages/api/ai/sql/parse-client-code.ts@@ -0,0 +1,85 @@+import { generateText, Output } from 'ai'+import { source } from 'common-tags'+import { NextApiRequest, NextApiResponse } from 'next'+import { z } from 'zod'++import { getModel } from '@/lib/ai/model'+import { DEFAULT_COMPLETION_MODEL } from '@/lib/ai/model.utils'+import apiWrapper from '@/lib/api/apiWrapper'++const codeSchema = z.object({+ sql: z+ .string()+ .optional()+ .describe(+ 'The converted SQL query from the provided client library code. Return undefined if the code is invalid'+ ),+ valid: z.boolean().describe('Whether the provided client library code is valid.'),+})++async function handler(req: NextApiRequest, res: NextApiResponse) {+ const { method } = req++ switch (method) {+ case 'POST':+ return handlePost(req, res)+ default:+ res.setHeader('Allow', ['POST'])+ res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })+ }+}++export async function handlePost(req: NextApiRequest, res: NextApiResponse) {+ const {+ body: { code },+ } = req++ if (!code) return res.status(400).json({ error: 'Code is required' })++ try {+ const { modelParams, error: modelError } = await getModel({+ provider: 'openai',+ modelEntry: DEFAULT_COMPLETION_MODEL,+ })++ if (modelError) {+ return res.status(500).json({ error: modelError.message })+ }++ const result = await generateText({+ ...modelParams,+ output: Output.object({ schema: codeSchema }),+ prompt: source`+ Convert the follow Supabase client library code into SQL. The response should only be in JSON with the structure: { sql: string, valid: boolean }+ If the client library code does not look valid, return { sql: undefined, valid: false }. Otherwise return valid as true and sql as the converted SQL query++ ${code}+ `,+ })++ return res.json(result.output)+ } catch (error) {+ if (error instanceof Error) {+ console.error(`Code parsing to SQL failed: ${error.message}`)++ // Check for context length error+ if (error.message.includes('context_length') || error.message.includes('too long')) {+ return res.status(400).json({+ error:+ 'The provided code snippet is too large for Supabase Assistant to ingest. Try splitting it into smaller queries.',+ })+ }+ } else {+ console.log(`Unknown error: ${error}`)+ }++ return res.status(500).json({+ error: 'There was an unknown error parsing the client library code. Please try again.',+ })+ }+}++const wrapper = (req: NextApiRequest, res: NextApiResponse) =>+ apiWrapper(req, res, handler, { withAuth: true })++export default wrapperdiff --git a/apps/studio/pages/api/content/graphql.ts b/apps/studio/pages/api/content/graphql.tsindex a053ad28715..a9c93256015 100644--- a/apps/studio/pages/api/content/graphql.ts+++ b/apps/studio/pages/api/content/graphql.ts@@ -2,8 +2,6 @@ import { NextApiRequest, NextApiResponse } from 'next'const CONTENT_API_URL = process.env.NEXT_PUBLIC_CONTENT_API_URL!-// Default export needed by Next.js convention-// eslint-disable-next-line no-restricted-exportsexport default async function handler(req: NextApiRequest, res: NextApiResponse) {if (req.method !== 'POST') {res.setHeader('Allow', ['POST'])diff --git a/apps/studio/pages/api/parse-query.ts b/apps/studio/pages/api/parse-query.tsnew file mode 100644index 00000000000..4ca8ce1e5cb--- /dev/null+++ b/apps/studio/pages/api/parse-query.ts@@ -0,0 +1,65 @@+import { parse } from 'libpg-query'+import { NextApiRequest, NextApiResponse } from 'next'++const getOperation = async (sql: string) => {+ const ast = await parse(sql)+ const stmt = ast.stmts?.[0]?.stmt++ if (!stmt) return null++ if ('SelectStmt' in stmt) return 'SELECT'+ if ('InsertStmt' in stmt) return 'INSERT'+ if ('UpdateStmt' in stmt) return 'UPDATE'+ if ('DeleteStmt' in stmt) return 'DELETE'+}++const getTablesInQuery = async (sql: string) => {+ const ast = await parse(sql)+ const tables: string[] = []++ function traverse(node: unknown): void {+ if (!node || typeof node !== 'object') return+ const obj = node as Record<string, unknown>++ if ('RangeVar' in obj) {+ const rv = obj.RangeVar as { relname?: string; schemaname?: string }+ if (rv.relname) tables.push(rv.schemaname ? `${rv.schemaname}.${rv.relname}` : rv.relname)+ }++ if ('relation' in obj && obj.relation && typeof obj.relation === 'object') {+ const rv = obj.relation as { relname?: string; schemaname?: string }+ if (rv.relname) tables.push(rv.schemaname ? `${rv.schemaname}.${rv.relname}` : rv.relname)+ }++ for (const value of Object.values(obj)) {+ Array.isArray(value) ? value.forEach(traverse) : traverse(value)+ }+ }++ traverse(ast)+ return [...new Set(tables)].sort((a, b) => a.localeCompare(b))+}++export default async function handler(req: NextApiRequest, res: NextApiResponse) {+ if (req.method !== 'POST') {+ res.setHeader('Allow', ['POST'])+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` })+ }++ try {+ const { sql } = req.body++ if (typeof sql !== 'string' || sql.trim().length === 0) {+ return res.status(400).json({ error: 'Missing or invalid "sql" in request body' })+ }++ const tables = await getTablesInQuery(sql)+ const operation = await getOperation(sql)+ return res.status(200).json({ tables, operation })+ } catch (error) {+ const message =+ (error as { sqlDetails?: { message?: string } })?.sqlDetails?.message ??+ (error instanceof Error ? error.message : 'Failed to parse SQL')+ return res.status(400).json({ error: message })+ }+}diff --git a/apps/studio/pages/project/[ref]/auth/policies.tsx b/apps/studio/pages/project/[ref]/auth/policies.tsxindex 6f3924926ad..c1b914e37ad 100644--- a/apps/studio/pages/project/[ref]/auth/policies.tsx+++ b/apps/studio/pages/project/[ref]/auth/policies.tsx@@ -20,11 +20,13 @@ import { PageSection, PageSectionContent } from 'ui-patterns/PageSection'import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'import { useIsInlineEditorEnabled } from '@/components/interfaces/Account/Preferences/useDashboardSettings'+import { useIsRLSTesterEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'import { Policies } from '@/components/interfaces/Auth/Policies/Policies'import { PoliciesDataProvider } from '@/components/interfaces/Auth/Policies/PoliciesDataContext'import { getGeneralPolicyTemplates } from '@/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModal.constants'import { PolicyEditorPanel } from '@/components/interfaces/Auth/Policies/PolicyEditorPanel'import { generatePolicyUpdateSQL } from '@/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRow.utils'+import { RLSTesterSheet } from '@/components/interfaces/Auth/RLSTester/RLSTesterSheet'import AuthLayout from '@/components/layouts/AuthLayout/AuthLayout'import { DefaultLayout } from '@/components/layouts/DefaultLayout'import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'@@ -109,7 +111,10 @@ const AuthPoliciesPage: NextPageWithLayout = () => {const { ref: projectRef } = useParams()const { data: project } = useSelectedProjectQuery()const { data: postgrestConfig } = useProjectPostgrestConfigQuery({ projectRef: project?.ref })+const isInlineEditorEnabled = useIsInlineEditorEnabled()+ const rlsTesterEnabled = useIsRLSTesterEnabled()+const { openSidebar } = useSidebarManagerSnapshot()const {setValue: setEditorPanelValue,@@ -274,6 +279,7 @@ const AuthPoliciesPage: NextPageWithLayout = () => {</PageHeaderSummary><PageHeaderAside><DocsButton href={`${DOCS_URL}/learn/auth-deep-dive/auth-row-level-security`} />+ {rlsTesterEnabled && <RLSTesterSheet handleSelectEditPolicy={handleSelectEditPolicy} />}</PageHeaderAside></PageHeaderMeta></PageHeader>diff --git a/apps/studio/proxy.ts b/apps/studio/proxy.tsindex 3ea62613ced..2ca590998b7 100644--- a/apps/studio/proxy.ts+++ b/apps/studio/proxy.ts@@ -18,6 +18,7 @@ const HOSTED_SUPPORTED_API_URLS = ['/ai/onboarding/design','/ai/feedback/classify','/ai/docs',+ '/ai/sql/parse-client-code','/get-ip-address','/get-utc-time','/get-deployment-commit',@@ -30,6 +31,7 @@ const HOSTED_SUPPORTED_API_URLS = ['/status-override','/api/integrations/stripe-sync','/content/graphql',+ '/parse-query',]export function proxy(request: NextRequest) {diff --git a/apps/studio/public/img/previews/rls-tester-preview.png b/apps/studio/public/img/previews/rls-tester-preview.pngnew file mode 100644index 00000000000..c21ed334276Binary files /dev/null and b/apps/studio/public/img/previews/rls-tester-preview.png differdiff --git a/apps/studio/state/role-impersonation-state.tsx b/apps/studio/state/role-impersonation-state.tsxindex 0ff8894a824..5cc2b9f522f 100644--- a/apps/studio/state/role-impersonation-state.tsx+++ b/apps/studio/state/role-impersonation-state.tsx@@ -125,3 +125,20 @@ export function useSubscribeToImpersonatedRole(export function isRoleImpersonationEnabled(impersonationRole?: ImpersonationRole) {return impersonationRole?.type === 'postgrest'}++export const getImpersonatedUser = (state: RoleImpersonationState) => {+ return state.role?.type === 'postgrest' &&+ state.role.role === 'authenticated' &&+ state.role.userType === 'native'+ ? state.role.user+ : undefined+}++export const getImpersonatedExternalAuth = (state: RoleImpersonationState) => {+ return state.role?.type === 'postgrest' &&+ state.role.role === 'authenticated' &&+ state.role.userType === 'external' &&+ state.role.externalAuth+ ? state.role.externalAuth.sub+ : undefined+}diff --git a/packages/common/constants/local-storage.ts b/packages/common/constants/local-storage.tsindex acd289ad04d..96e382385c4 100644--- a/packages/common/constants/local-storage.ts+++ b/packages/common/constants/local-storage.ts@@ -25,6 +25,7 @@ export const LOCAL_STORAGE_KEYS = {UI_PREVIEW_FLOATING_MOBILE_TOOLBAR: 'supabase-ui-floating-mobile-toolbar',UI_PREVIEW_PLATFORM_WEBHOOKS: 'supabase-ui-platform-webhooks',UI_PREVIEW_JIT_DB_ACCESS: 'supabase-ui-jit-db-access',+ UI_PREVIEW_RLS_TESTER: 'supabase-ui-rls-tester',NEW_LAYOUT_NOTICE_ACKNOWLEDGED: 'new-layout-notice-acknowledge',TABS_INTERFACE_ACKNOWLEDGED: 'tabs-interface-acknowledge',diff --git a/packages/pg-meta/src/sql/studio/database/check-tables-rls-enabled.ts b/packages/pg-meta/src/sql/studio/database/check-tables-rls-enabled.tsnew file mode 100644index 00000000000..1a2ed7be970--- /dev/null+++ b/packages/pg-meta/src/sql/studio/database/check-tables-rls-enabled.ts@@ -0,0 +1,24 @@+import { joinSqlFragments, literal, safeSql, SafeSqlFragment } from '../../../pg-format'++export const getTablesRlsEnabledStatusSQL = ({+ tables,+}: {+ tables: { schema: string; table: string }[]+}): SafeSqlFragment => {+ const tableNames = joinSqlFragments(+ tables.map((x) => literal(`${x.schema}.${x.table}`)),+ ', '+ )++ return safeSql`+ SELECT+ n.nspname AS schema,+ c.relname AS table,+ c.relrowsecurity AS rls_enabled+FROM pg_class c+JOIN pg_namespace n ON n.oid = c.relnamespace+WHERE (n.nspname || '.' || c.relname) = ANY(+ ARRAY[${tableNames}]+);+`+}diff --git a/packages/pg-meta/src/sql/studio/database/index.ts b/packages/pg-meta/src/sql/studio/database/index.tsindex 0954bbafcf0..380e941f0b1 100644--- a/packages/pg-meta/src/sql/studio/database/index.ts+++ b/packages/pg-meta/src/sql/studio/database/index.ts@@ -1,5 +1,6 @@export * from './check-tables-anon-authenticated-access'export * from './check-tables-without-rls'+export * from './check-tables-rls-enabled'export * from './columns'export * from './cron-jobs'export * from './extensions'