The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): warn before CREATE TABLE without RLS in SQL editor (#45008)
Alaister Young3aed9a9a2a81
diff --git a/apps/studio/components/interfaces/SQLEditor/RunQueryWarningModal.tsx b/apps/studio/components/interfaces/SQLEditor/RunQueryWarningModal.tsxindex fa27e55bc6a..81daa60ed73 100644--- a/apps/studio/components/interfaces/SQLEditor/RunQueryWarningModal.tsx+++ b/apps/studio/components/interfaces/SQLEditor/RunQueryWarningModal.tsx@@ -1,13 +1,25 @@-import { DialogSectionSeparator, Separator } from 'ui'-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'+import {+ Button,+ cn,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogSection,+ DialogSectionSeparator,+ DialogTitle,+} from 'ui'+import { Admonition } from 'ui-patterns'import { PotentialIssues } from './SQLEditor.types'+import { DOCS_URL } from '@/lib/constants'interface RunQueryWarningModalProps {visible: booleanpotentialIssues: PotentialIssues | undefinedonCancel: () => voidonConfirm: () => void+ onConfirmWithRLS?: () => void}export const RunQueryWarningModal = ({@@ -15,63 +27,135 @@ export const RunQueryWarningModal = ({potentialIssues,onCancel,onConfirm,+ onConfirmWithRLS,}: RunQueryWarningModalProps) => {- const { hasDestructiveOperations, hasUpdateWithoutWhere, hasAlterDatabasePreventConnection } =- potentialIssues || {}+ const {+ hasDestructiveOperations,+ hasUpdateWithoutWhere,+ hasAlterDatabasePreventConnection,+ createTablesMissingRLS,+ } = potentialIssues || {}++ const missingRLSTables = createTablesMissingRLS ?? []+ const hasMissingRLS = missingRLSTables.length > 0+ const issueCount =+ (hasDestructiveOperations ? 1 : 0) ++ (hasUpdateWithoutWhere ? 1 : 0) ++ (hasAlterDatabasePreventConnection ? 1 : 0) ++ (hasMissingRLS ? 1 : 0)return (- <ConfirmationModal- visible={visible}- size="large"- title={`Potential issue${hasDestructiveOperations && hasUpdateWithoutWhere ? 's' : ''} detected with your query`}- confirmLabel="Run this query"- variant="warning"- alert={{- base: {- variant: 'warning',- },- title:- hasDestructiveOperations && hasUpdateWithoutWhere- ? 'The following potential issues have been detected:'- : 'The following potential issue has been detected:',- description: 'Ensure that these are intentional before executing this query',+ <Dialog+ open={visible}+ onOpenChange={(open) => {+ if (!open) onCancel()}}- onCancel={onCancel}- onConfirm={onConfirm}>- <div className="text-sm">- <ul className="border rounded-md grid bg-surface-200 divide-y">- {hasDestructiveOperations && (- <li className="grid pt-3 pb-2 px-4">- <span className="font-bold">Query has destructive operations</span>- <span className="text-foreground-light">- Make sure you are not accidentally removing something important.- </span>- </li>- )}- {hasUpdateWithoutWhere && (- <li className="grid pt-2 pb-3 px-4 gap-1">- <span className="font-bold">Query uses update without a where clause</span>- <span className="text-foreground-light">- Without a <code className="text-code-inline">where</code> clause, this could update- all rows in the table.- </span>- </li>- )}- {hasAlterDatabasePreventConnection && (- <li className="grid pt-2 pb-3 px-4 gap-1">- <span className="font-bold">Query will prevent connections to your database</span>- <span className="text-foreground-light">- The dashboard will no longer have access to your database, and you will need a- direct connection to your database to reconfigure this setting- </span>- </li>+ <DialogContent aria-describedby={undefined} className="p-0 gap-0 pb-5 !block" size="large">+ <DialogHeader className={cn('border-b')} padding="small">+ <DialogTitle>+ {`Potential issue${issueCount > 1 ? 's' : ''} detected with your query`}+ </DialogTitle>+ <DialogDescription className="sr-only">+ Review the warnings below before running this query.+ </DialogDescription>+ </DialogHeader>++ <Admonition+ type="warning"+ label={+ issueCount > 1+ ? 'The following potential issues have been detected:'+ : 'The following potential issue has been detected:'+ }+ description="Ensure that these are intentional before executing this query"+ className="border-x-0 rounded-none -mt-px"+ />++ <DialogSection padding="small">+ <div className="text-sm">+ <ul className="border rounded-md grid bg-surface-200 divide-y">+ {hasDestructiveOperations && (+ <li className="grid pt-3 pb-2 px-4">+ <span className="font-bold">Query has destructive operations</span>+ <span className="text-foreground-light">+ Make sure you are not accidentally removing something important.+ </span>+ </li>+ )}+ {hasUpdateWithoutWhere && (+ <li className="grid pt-2 pb-3 px-4 gap-1">+ <span className="font-bold">Query uses update without a where clause</span>+ <span className="text-foreground-light">+ Without a <code className="text-code-inline">where</code> clause, this could+ update all rows in the table.+ </span>+ </li>+ )}+ {hasAlterDatabasePreventConnection && (+ <li className="grid pt-2 pb-3 px-4 gap-1">+ <span className="font-bold">Query will prevent connections to your database</span>+ <span className="text-foreground-light">+ The dashboard will no longer have access to your database, and you will need a+ direct connection to your database to reconfigure this setting+ </span>+ </li>+ )}+ {hasMissingRLS && (+ <li className="grid pt-2 pb-3 px-4 gap-1">+ <span className="font-bold">+ {missingRLSTables.length === 1+ ? 'New table will not have Row Level Security enabled'+ : 'New tables will not have Row Level Security enabled'}+ </span>+ <span className="text-foreground-light">+ Without RLS, any client using your project's anon or authenticated keys can read+ and write to{' '}+ {missingRLSTables.length === 1 ? (+ <code className="text-code-inline">+ {missingRLSTables[0].schema+ ? `${missingRLSTables[0].schema}.${missingRLSTables[0].tableName}`+ : missingRLSTables[0].tableName}+ </code>+ ) : (+ 'these tables'+ )}+ . Enable RLS and add policies before exposing this table via the API.{' '}+ <a+ href={`${DOCS_URL}/guides/database/postgres/row-level-security`}+ target="_blank"+ rel="noreferrer"+ className="underline"+ >+ Learn more+ </a>+ .+ </span>+ </li>+ )}+ </ul>+ </div>+ <p className="mt-4 text-sm text-foreground-light">+ Please confirm that you would like to execute this query.+ </p>+ </DialogSection>++ <DialogSectionSeparator />++ <div className="flex flex-wrap gap-2 px-5 pt-5">+ <Button size="medium" type="default" onClick={() => onCancel()}>+ Cancel+ </Button>+ <Button size="medium" type="warning" onClick={onConfirm} className="ml-auto">+ {hasMissingRLS ? 'Run without RLS' : 'Run this query'}+ </Button>+ {hasMissingRLS && onConfirmWithRLS && (+ <Button size="medium" type="primary" onClick={onConfirmWithRLS}>+ Run and enable RLS+ </Button>)}- </ul>- </div>- <p className="mt-4 text-sm text-foreground-light">- Please confirm that you would like to execute this query.- </p>- </ConfirmationModal>+ </div>+ </DialogContent>+ </Dialog>)}diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsxindex 6e9b3477947..f3c2f1528b2 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx@@ -38,10 +38,14 @@ import {type PotentialIssues,} from './SQLEditor.types'import {+ appendEnableRLSStatements,checkAlterDatabaseConnection,checkDestructiveQuery,checkIfAppendLimitRequired,createSqlSnippetSkeletonV2,+ filterTablesCoveredByEnsureRLSTrigger,+ getCreateTablesMissingRLS,+ hasActiveEnsureRLSTrigger,isUpdateWithoutWhere,suffixWithLimit,} from './SQLEditor.utils'@@ -56,6 +60,7 @@ import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/Limport ResizableAIWidget from '@/components/ui/AIEditor/ResizableAIWidget'import { GridFooter } from '@/components/ui/GridFooter'import { useSqlTitleGenerateMutation } from '@/data/ai/sql-title-mutation'+import { useDatabaseEventTriggersQuery } from '@/data/database-event-triggers/database-event-triggers-query'import { constructHeaders, isValidConnString } from '@/data/fetchers'import { lintKeys } from '@/data/lint/keys'import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query'@@ -177,6 +182,14 @@ export const SQLEditor = () => {{ enabled: isValidConnString(project?.connectionString) })+ const { data: eventTriggers } = useDatabaseEventTriggersQuery(+ {+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ },+ { enabled: isValidConnString(project?.connectionString) }+ )+/* React query mutations */const { mutateAsync: generateSqlTitle } = useSqlTitleGenerateMutation()const { mutate: sendEvent } = useSendEventMutation()@@ -298,7 +311,7 @@ export const SQLEditor = () => {}, [id, isDiffOpen, project, snapV2])const executeQuery = useCallback(- async (force: boolean = false) => {+ async (force: boolean = false, sqlOverride?: string) => {if (isDiffOpen) {clearPendingRunRefocus()return@@ -317,23 +330,32 @@ export const SQLEditor = () => {const selection = editor.getSelection()const selectedValue = selection ? editor.getModel()?.getValueInRange(selection) : undefined- const sql = snippet+ const editorSql = snippet? ((selectedValue || editorRef.current?.getValue()) ?? snippet.snippet.content?.sql): selectedValue || editorRef.current?.getValue()+ const sql = sqlOverride ?? editorSqlconst hasDestructiveOperations = checkDestructiveQuery(sql)const hasUpdateWithoutWhere = isUpdateWithoutWhere(sql)const hasAlterDatabasePreventConnection = checkAlterDatabaseConnection(sql)+ const createTablesMissingRLS = filterTablesCoveredByEnsureRLSTrigger(+ getCreateTablesMissingRLS(sql),+ hasActiveEnsureRLSTrigger(eventTriggers)+ )const queryHasIssues =!force &&- (hasDestructiveOperations || hasUpdateWithoutWhere || hasAlterDatabasePreventConnection)+ (hasDestructiveOperations ||+ hasUpdateWithoutWhere ||+ hasAlterDatabasePreventConnection ||+ createTablesMissingRLS.length > 0)if (queryHasIssues) {setPotentialIssues({hasDestructiveOperations,hasUpdateWithoutWhere,hasAlterDatabasePreventConnection,+ createTablesMissingRLS,})return}@@ -395,6 +417,7 @@ export const SQLEditor = () => {setAiTitle,databaseSelectorState.selectedDatabaseId,databases,+ eventTriggers,limit,])@@ -816,6 +839,21 @@ export const SQLEditor = () => {refocusEditor()void executeQuery(true)}}+ onConfirmWithRLS={() => {+ const tables = potentialIssues?.createTablesMissingRLS ?? []+ if (tables.length === 0) return+ const editor = editorRef.current+ const selection = editor?.getSelection()+ const selectedValue = selection+ ? editor?.getModel()?.getValueInRange(selection)+ : undefined+ const baseSql = selectedValue || editor?.getValue() || ''+ const rewrittenSql = appendEnableRLSStatements(baseSql, tables)+ shouldRefocusAfterRunRef.current = true+ setPotentialIssues(undefined)+ refocusEditor()+ void executeQuery(true, rewrittenSql)+ }}/><div className="flex h-full">diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.types.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.types.tsindex 092bd1a6422..185196f6fcc 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.types.ts+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.types.ts@@ -35,4 +35,5 @@ export type PotentialIssues = {hasDestructiveOperations?: booleanhasUpdateWithoutWhere?: booleanhasAlterDatabasePreventConnection?: boolean+ createTablesMissingRLS?: { schema?: string; tableName: string }[]}diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.tsindex e6a9a109571..70be6d89c71 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts@@ -2,12 +2,30 @@ import { stripIndent } from 'common-tags'import { describe, expect, it, test } from 'vitest'import {+ appendEnableRLSStatements,checkAlterDatabaseConnection,checkDestructiveQuery,checkIfAppendLimitRequired,+ filterTablesCoveredByEnsureRLSTrigger,+ getCreateTablesMissingRLS,+ hasActiveEnsureRLSTrigger,isUpdateWithoutWhere,suffixWithLimit,} from './SQLEditor.utils'+import type { DatabaseEventTrigger } from '@/data/database-event-triggers/database-event-triggers-query'++const buildTrigger = (overrides: Partial<DatabaseEventTrigger> = {}): DatabaseEventTrigger => ({+ oid: 1,+ name: 'ensure_rls',+ event: 'ddl_command_end',+ enabled_mode: 'ORIGIN',+ tags: ['CREATE TABLE'],+ function_name: 'rls_auto_enable',+ function_schema: 'public',+ owner: 'postgres',+ function_definition: null,+ ...overrides,+})describe('SQLEditor.utils.ts:checkIfAppendLimitRequired', () => {test('Should return false if limit passed is <= 0', () => {@@ -263,6 +281,240 @@ describe('SQLEditor.utils:updateWithoutWhere', () => {})})+describe('SQLEditor.utils:getCreateTablesMissingRLS', () => {+ it('flags a basic CREATE TABLE without RLS', () => {+ const result = getCreateTablesMissingRLS('create table foo (id int8 primary key);')+ expect(result).toEqual([{ schema: undefined, tableName: 'foo' }])+ })++ it('flags CREATE TABLE IF NOT EXISTS', () => {+ const result = getCreateTablesMissingRLS(+ 'create table if not exists foo (id int8 primary key);'+ )+ expect(result).toHaveLength(1)+ expect(result[0].tableName).toBe('foo')+ })++ it('flags schema-qualified CREATE TABLE', () => {+ const result = getCreateTablesMissingRLS('create table public.foo (id int8 primary key);')+ expect(result).toEqual([{ schema: 'public', tableName: 'foo' }])+ })++ it('flags quoted identifiers', () => {+ const result = getCreateTablesMissingRLS(+ 'create table "public"."user_table" (id int8 primary key);'+ )+ expect(result).toEqual([{ schema: 'public', tableName: 'user_table' }])+ })++ it('flags quoted identifiers containing spaces', () => {+ const result = getCreateTablesMissingRLS(+ 'create table "public"."My Table" (id int8 primary key);'+ )+ expect(result).toEqual([{ schema: 'public', tableName: 'My Table' }])+ })++ it('matches RLS to a table whose name contains spaces', () => {+ const sql = stripIndent`+ create table "My Table" (id int8 primary key);+ alter table "My Table" enable row level security;+ `+ expect(getCreateTablesMissingRLS(sql)).toEqual([])+ })++ it('does not flag when ENABLE ROW LEVEL SECURITY is in the same SQL', () => {+ const sql = stripIndent`+ create table foo (id int8 primary key);+ alter table foo enable row level security;+ `+ expect(getCreateTablesMissingRLS(sql)).toEqual([])+ })++ it('does not flag when ENABLE RLS shorthand is in the same SQL', () => {+ const sql = stripIndent`+ create table foo (id int8 primary key);+ alter table foo enable rls;+ `+ expect(getCreateTablesMissingRLS(sql)).toEqual([])+ })++ it('matches RLS to the right table when multiple tables created', () => {+ const sql = stripIndent`+ create table foo (id int8 primary key);+ create table bar (id int8 primary key);+ alter table foo enable row level security;+ `+ const result = getCreateTablesMissingRLS(sql)+ expect(result).toHaveLength(1)+ expect(result[0].tableName).toBe('bar')+ })++ it('does not flag when CREATE TABLE is inside a comment', () => {+ const sql = stripIndent`+ -- create table foo (id int8 primary key);+ select 1;+ `+ expect(getCreateTablesMissingRLS(sql)).toEqual([])+ })++ it('does not flag when there is no CREATE TABLE at all', () => {+ expect(getCreateTablesMissingRLS('select * from foo;')).toEqual([])+ })++ it('schema-qualified RLS matches schema-qualified CREATE', () => {+ const sql = stripIndent`+ create table public.foo (id int8 primary key);+ alter table public.foo enable row level security;+ `+ expect(getCreateTablesMissingRLS(sql)).toEqual([])+ })++ it('flags CREATE TEMP TABLE', () => {+ const result = getCreateTablesMissingRLS('create temp table foo (id int8 primary key);')+ expect(result).toHaveLength(1)+ expect(result[0].tableName).toBe('foo')+ })++ it('does not collide quoted identifiers that differ only by case', () => {+ // "MyTable" and "mytable" are distinct tables in Postgres, so the ALTER+ // here targets a different table than the CREATE — the warning must fire.+ const sql = stripIndent`+ create table "MyTable" (id int8 primary key);+ alter table "mytable" enable row level security;+ `+ const result = getCreateTablesMissingRLS(sql)+ expect(result).toHaveLength(1)+ expect(result[0].tableName).toBe('MyTable')+ })+})++describe('SQLEditor.utils:appendEnableRLSStatements', () => {+ it('appends a single ALTER TABLE ENABLE RLS statement', () => {+ const result = appendEnableRLSStatements('create table foo (id int8 primary key);', [+ { tableName: 'foo' },+ ])+ expect(result).toContain('ALTER TABLE foo ENABLE ROW LEVEL SECURITY;')+ })++ it('appends one ALTER per table', () => {+ const result = appendEnableRLSStatements(+ 'create table foo (id int8); create table bar (id int8);',+ [{ tableName: 'foo' }, { tableName: 'bar' }]+ )+ expect(result).toContain('ALTER TABLE foo ENABLE ROW LEVEL SECURITY;')+ expect(result).toContain('ALTER TABLE bar ENABLE ROW LEVEL SECURITY;')+ })++ it('schema-qualifies the table when schema is provided', () => {+ const result = appendEnableRLSStatements('create table public.foo (id int8);', [+ { schema: 'public', tableName: 'foo' },+ ])+ expect(result).toContain('ALTER TABLE public.foo ENABLE ROW LEVEL SECURITY;')+ })++ it('quotes identifiers that are not simple', () => {+ const result = appendEnableRLSStatements('create table "My Table" (id int8);', [+ { tableName: 'My Table' },+ ])+ expect(result).toContain('ALTER TABLE "My Table" ENABLE ROW LEVEL SECURITY;')+ })++ it('quotes mixed-case identifiers so Postgres does not fold them to lowercase', () => {+ const result = appendEnableRLSStatements('create table "MyTable" (id int8);', [+ { tableName: 'MyTable' },+ ])+ expect(result).toContain('ALTER TABLE "MyTable" ENABLE ROW LEVEL SECURITY;')+ })++ it('quotes mixed-case schema and table identifiers', () => {+ const result = appendEnableRLSStatements('create table "MySchema"."MyTable" (id int8);', [+ { schema: 'MySchema', tableName: 'MyTable' },+ ])+ expect(result).toContain('ALTER TABLE "MySchema"."MyTable" ENABLE ROW LEVEL SECURITY;')+ })++ it('returns the original SQL unchanged when there are no tables', () => {+ const sql = 'select 1;'+ expect(appendEnableRLSStatements(sql, [])).toBe(sql)+ })++ it('puts the terminator on its own line when SQL ends with a line comment', () => {+ // Without this, the appended ';' would be swallowed by the line comment and+ // the following ALTER TABLE would be parsed as part of the CREATE TABLE.+ const sql = stripIndent`+ create table foo (id int)+ -- forgot the semicolon+ `+ const result = appendEnableRLSStatements(sql, [{ tableName: 'foo' }])+ expect(result).toMatch(/-- forgot the semicolon\n;\n/)+ expect(result).toContain('ALTER TABLE foo ENABLE ROW LEVEL SECURITY;')+ })+})++describe('SQLEditor.utils:hasActiveEnsureRLSTrigger', () => {+ it('returns false for undefined triggers', () => {+ expect(hasActiveEnsureRLSTrigger(undefined)).toBe(false)+ })++ it('returns false for an empty list', () => {+ expect(hasActiveEnsureRLSTrigger([])).toBe(false)+ })++ it('returns true when a trigger named "ensure_rls" is active', () => {+ expect(hasActiveEnsureRLSTrigger([buildTrigger()])).toBe(true)+ })++ it('returns true when a trigger uses the rls_auto_enable function (renamed trigger)', () => {+ expect(+ hasActiveEnsureRLSTrigger([+ buildTrigger({ name: 'something_else', function_name: 'rls_auto_enable' }),+ ])+ ).toBe(true)+ })++ it('returns false when the matching trigger is DISABLED', () => {+ expect(hasActiveEnsureRLSTrigger([buildTrigger({ enabled_mode: 'DISABLED' })])).toBe(false)+ })++ it('ignores unrelated triggers', () => {+ expect(+ hasActiveEnsureRLSTrigger([buildTrigger({ name: 'audit_log', function_name: 'log_changes' })])+ ).toBe(false)+ })+})++describe('SQLEditor.utils:filterTablesCoveredByEnsureRLSTrigger', () => {+ it('returns the input unchanged when the trigger is not present', () => {+ const tables = [{ tableName: 'foo' }, { schema: 'private', tableName: 'bar' }]+ expect(filterTablesCoveredByEnsureRLSTrigger(tables, false)).toEqual(tables)+ })++ it('drops public-schema tables when the trigger is present', () => {+ const tables = [+ { schema: 'public', tableName: 'foo' },+ { tableName: 'bar' }, // no schema → defaults to public+ ]+ expect(filterTablesCoveredByEnsureRLSTrigger(tables, true)).toEqual([])+ })++ it('keeps tables in non-public schemas when the trigger is present', () => {+ const tables = [+ { schema: 'public', tableName: 'foo' },+ { schema: 'private', tableName: 'bar' },+ { schema: 'app', tableName: 'baz' },+ ]+ expect(filterTablesCoveredByEnsureRLSTrigger(tables, true)).toEqual([+ { schema: 'private', tableName: 'bar' },+ { schema: 'app', tableName: 'baz' },+ ])+ })++ it('matches the public schema case-insensitively', () => {+ const tables = [{ schema: 'PUBLIC', tableName: 'foo' }]+ expect(filterTablesCoveredByEnsureRLSTrigger(tables, true)).toEqual([])+ })+})+describe('SQLEditor.utils:checkAlterDatabaseConnection', () => {it('detects connection limit 0', () => {const match = checkAlterDatabaseConnection('alter database postgres connection limit 0;')diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.tsindex b638d619a1e..2c022ada17b 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts@@ -1,3 +1,5 @@+import { TABLE_EVENT_ACTIONS } from 'common/telemetry-constants'+import {alterDatabasePreventConnectionStatements,destructiveSqlRegex,@@ -6,10 +8,44 @@ import {updateWithoutWhereRegex,} from './SQLEditor.constants'import { ContentDiff } from './SQLEditor.types'+import type { DatabaseEventTrigger } from '@/data/database-event-triggers/database-event-triggers-query'import { generateUuid } from '@/lib/api/snippets.browser'import { removeCommentsFromSql } from '@/lib/helpers'+import { sqlEventParser } from '@/lib/sql-event-parser'import type { SnippetWithContent } from '@/state/sql-editor-v2'+export type CreateTableWithoutRLS = {+ schema?: string+ tableName: string+}++// The ensure_rls event trigger only auto-enables RLS on tables in the public+// schema (see AUTO_ENABLE_RLS_EVENT_TRIGGER_SQL).+const ENSURE_RLS_TRIGGER_SCHEMAS = new Set(['public'])++export function hasActiveEnsureRLSTrigger(triggers: DatabaseEventTrigger[] | undefined) {+ return (+ triggers?.some(+ (t) =>+ (t.name === 'ensure_rls' || t.function_name === 'rls_auto_enable') &&+ t.enabled_mode !== 'DISABLED'+ ) ?? false+ )+}++/**+ * Filters out CREATE TABLE entries that will be covered by the project's+ * ensure_rls event trigger (which only handles tables in the public schema).+ * Tables in any other schema are returned unchanged so the user is still warned.+ */+export function filterTablesCoveredByEnsureRLSTrigger(+ tables: CreateTableWithoutRLS[],+ hasTrigger: boolean+): CreateTableWithoutRLS[] {+ if (!hasTrigger) return tables+ return tables.filter((t) => !ENSURE_RLS_TRIGGER_SCHEMAS.has((t.schema ?? 'public').toLowerCase()))+}+export const createSqlSnippetSkeletonV2 = ({name,sql,@@ -65,6 +101,62 @@ export function isUpdateWithoutWhere(sql: string): boolean {)}+/**+ * Returns CREATE TABLE statements in `sql` that do not have a matching+ * ALTER TABLE ... ENABLE ROW LEVEL SECURITY in the same SQL submission.+ *+ * Operates on the SQL passed in (which is the user's selection if any, or the+ * full editor contents otherwise) so partial-execution selects work naturally.+ */+export function getCreateTablesMissingRLS(sql: string): CreateTableWithoutRLS[] {+ const events = sqlEventParser.getTableEvents(sql)++ // Match case-sensitively. Lowercasing would let quoted identifiers like+ // "MyTable" and "mytable" — which are different tables in Postgres — collide+ // and silently suppress the warning. The trade-off is rare false positives+ // when users mix case for *unquoted* identifiers (Postgres would have folded+ // them anyway), which is annoying but safe.+ const key = (e: { schema?: string; tableName?: string }) => `${e.schema ?? ''}.${e.tableName}`++ const rlsEnabled = new Set(+ events.filter((e) => e.type === TABLE_EVENT_ACTIONS.TableRLSEnabled && e.tableName).map(key)+ )++ return events+ .filter((e) => e.type === TABLE_EVENT_ACTIONS.TableCreated && e.tableName)+ .filter((e) => !rlsEnabled.has(key(e)))+ .map((e) => ({ schema: e.schema, tableName: e.tableName as string }))+}++/**+ * Appends `ALTER TABLE ... ENABLE ROW LEVEL SECURITY` statements to `sql`+ * for each provided table.+ */+export function appendEnableRLSStatements(sql: string, tables: CreateTableWithoutRLS[]) {+ if (tables.length === 0) return sql++ // Postgres folds unquoted identifiers to lowercase, so any identifier that+ // isn't strictly lowercase-safe (e.g. "MyTable", "user table") must be quoted+ // to refer back to the original table.+ const quote = (identifier: string) =>+ /^[a-z_][a-z0-9_]*$/.test(identifier) ? identifier : `"${identifier.replace(/"/g, '""')}"`++ const additions = tables+ .map(({ schema, tableName }) => {+ const target = schema ? `${quote(schema)}.${quote(tableName)}` : quote(tableName)+ return `ALTER TABLE ${target} ENABLE ROW LEVEL SECURITY;`+ })+ .join('\n')++ const trimmed = sql.replace(/\s+$/, '')+ // If the SQL ends with a line comment, the appended ';' would be swallowed,+ // so put the terminator on its own line.+ const endsWithLineComment = /--[^\r\n]*$/.test(trimmed)+ const separator = trimmed.endsWith(';') ? '\n\n' : endsWithLineComment ? '\n;\n\n' : ';\n\n'++ return `${trimmed}${separator}-- Added by Supabase: enable Row Level Security on newly created tables\n${additions}\n`+}+export function checkAlterDatabaseConnection(sql: string): boolean {const cleanedSql = removeCommentsFromSql(sql)const statements = cleanedSqldiff --git a/apps/studio/lib/sql-event-parser.ts b/apps/studio/lib/sql-event-parser.tsindex dece7fd5c85..7b098d3ff8b 100644--- a/apps/studio/lib/sql-event-parser.ts+++ b/apps/studio/lib/sql-event-parser.ts@@ -22,25 +22,25 @@ export class SQLEventParser {{type: TABLE_EVENT_ACTIONS.TableCreated,patterns: [- /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>[\w"`]+)/i,- /CREATE\s+TEMP(?:ORARY)?\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>[\w"`]+)/i,- /CREATE\s+UNLOGGED\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>[\w"`]+)/i,- /SELECT\s+.*?\s+INTO\s+(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>[\w"`]+)/is,- /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>[\w"`]+)\s+AS\s+SELECT/i,+ /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"(?:[^"]|"")+"|`(?:[^`]|``)+`|[\w]+))/i,+ /CREATE\s+TEMP(?:ORARY)?\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"(?:[^"]|"")+"|`(?:[^`]|``)+`|[\w]+))/i,+ /CREATE\s+UNLOGGED\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"(?:[^"]|"")+"|`(?:[^`]|``)+`|[\w]+))/i,+ /SELECT\s+.*?\s+INTO\s+(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"(?:[^"]|"")+"|`(?:[^`]|``)+`|[\w]+))/is,+ /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"(?:[^"]|"")+"|`(?:[^`]|``)+`|[\w]+))\s+AS\s+SELECT/i,],},{type: TABLE_EVENT_ACTIONS.TableDataAdded,patterns: [- /INSERT\s+INTO\s+(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>[\w"`]+)/i,- /COPY\s+(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>[\w"`]+)\s+FROM/i,+ /INSERT\s+INTO\s+(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"(?:[^"]|"")+"|`(?:[^`]|``)+`|[\w]+))/i,+ /COPY\s+(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"(?:[^"]|"")+"|`(?:[^`]|``)+`|[\w]+))\s+FROM/i,],},{type: TABLE_EVENT_ACTIONS.TableRLSEnabled,patterns: [- /ALTER\s+TABLE\s+(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>[\w"`]+).*?ENABLE\s+ROW\s+LEVEL\s+SECURITY/i,- /ALTER\s+TABLE\s+(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>[\w"`]+).*?ENABLE\s+RLS/i,+ /ALTER\s+TABLE\s+(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"(?:[^"]|"")+"|`(?:[^`]|``)+`|[\w]+)).*?ENABLE\s+ROW\s+LEVEL\s+SECURITY/i,+ /ALTER\s+TABLE\s+(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"(?:[^"]|"")+"|`(?:[^`]|``)+`|[\w]+)).*?ENABLE\s+RLS/i,],},]diff --git a/e2e/studio/features/sql-editor.spec.ts b/e2e/studio/features/sql-editor.spec.tsindex 6ab9b744d37..e537f65c157 100644--- a/e2e/studio/features/sql-editor.spec.ts+++ b/e2e/studio/features/sql-editor.spec.ts@@ -3,6 +3,7 @@ import { expect, Page } from '@playwright/test'import { env } from '../env.config.js'import { expectClipboardValue } from '../utils/clipboard.js'+import { dropTable, query } from '../utils/db/index.js'import { isCLI } from '../utils/is-cli.js'import { resetLocalStorage } from '../utils/reset-local-storage.js'import { test } from '../utils/test.js'@@ -289,6 +290,59 @@ test.describe('SQL Editor', () => {}})+ test('warns on CREATE TABLE without RLS and "Run and enable RLS" enables it', async ({ ref }) => {+ const tableName = 'pw_rls_smoke_test'++ // Drop any leftover table from a previous failed run, and ensure cleanup+ // after the test regardless of pass/fail.+ await dropTable(tableName)++ try {+ await expect(page.getByText('Loading...')).not.toBeVisible()+ await page.locator('.view-lines').click()+ await page.keyboard.press('ControlOrMeta+KeyA')+ await page.keyboard.type(`create table ${tableName} (id int8 primary key);`)++ await page.getByTestId('sql-run-button').click()++ // Modal appears with the RLS warning+ await expect(+ page.getByRole('heading', { name: 'Potential issue detected with' }),+ 'Warning modal should appear when CREATE TABLE has no RLS'+ ).toBeVisible()+ await expect(+ page.getByText('Row Level Security'),+ 'Modal should mention Row Level Security'+ ).toBeVisible()++ // Click "Run and enable RLS" — query runs with appended ALTER+ const sqlMutationPromise = waitForApiResponse(page, 'pg-meta', ref, 'query?key=', {+ method: 'POST',+ })+ await page.getByRole('button', { name: 'Run and enable RLS' }).click()+ await sqlMutationPromise++ // Verify the table was created with RLS enabled+ const rows = await query<{ relrowsecurity: boolean }>(+ `select c.relrowsecurity+ from pg_class c+ join pg_namespace n on n.oid = c.relnamespace+ where n.nspname = 'public' and c.relname = $1`,+ [tableName]+ )+ expect(rows[0]?.relrowsecurity, 'Table should exist and have RLS enabled').toBe(true)+ } finally {+ await dropTable(tableName)++ // clear SQL snippet+ if (!isCLI()) {+ await deleteSqlSnippet(page, ref, newSqlSnippetName)+ } else {+ await page.reload()+ }+ }+ })+test('should not show warning modal for safe alter database statement', async ({ ref }) => {await expect(page.getByText('Loading...')).not.toBeVisible()await page.locator('.view-lines').click()