Skip to content

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

[FE-4070] fix(studio): allow adding expressions to RLS policies (#48700)

Alaister Young0e71933ce3fa
diff --git a/apps/studio/components/interfaces/Database/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.test.ts b/apps/studio/components/interfaces/Database/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.test.ts
new file mode 100644
index 00000000000..65aae4e19d1
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.test.ts
@@ -0,0 +1,102 @@
+import type { PGPolicy } from '@supabase/pg-meta'
+import { describe, expect, it } from 'vitest'
+
+import { generateUpdatePolicyPayload } from './PolicyEditorPanel.utils'
+
+type PolicyFixture = Pick<PGPolicy, 'name' | 'roles' | 'command' | 'definition' | 'check'>
+
+const mockPolicy = (overrides: Partial<PolicyFixture> = {}): PolicyFixture => ({
+ name: 'my_policy',
+ roles: ['authenticated'],
+ command: 'DELETE',
+ definition: 'user_id = auth.uid()',
+ check: null,
+ ...overrides,
+})
+
+const baseForm = {
+ name: 'my_policy',
+ roles: ['authenticated'],
+ // The panel prefills editors with two leading spaces of indentation
+ using: ' user_id = auth.uid()',
+ check: undefined,
+}
+
+describe('generateUpdatePolicyPayload', () => {
+ it('returns an empty payload when nothing changed', () => {
+ expect(generateUpdatePolicyPayload(mockPolicy(), baseForm)).toEqual({})
+ })
+
+ it('includes the definition when a policy with a null definition gains a using expression', () => {
+ const payload = generateUpdatePolicyPayload(mockPolicy({ definition: null }), {
+ ...baseForm,
+ using: 'true',
+ })
+ expect(payload).toEqual({ definition: 'true' })
+ })
+
+ it('includes the definition when the using expression changed', () => {
+ const payload = generateUpdatePolicyPayload(mockPolicy(), { ...baseForm, using: 'true' })
+ expect(payload).toEqual({ definition: 'true' })
+ })
+
+ it('omits the definition when the using expression is empty', () => {
+ expect(generateUpdatePolicyPayload(mockPolicy(), { ...baseForm, using: '' })).toEqual({})
+ expect(generateUpdatePolicyPayload(mockPolicy(), { ...baseForm, using: ' ' })).toEqual({})
+ expect(generateUpdatePolicyPayload(mockPolicy(), { ...baseForm, using: undefined })).toEqual({})
+ })
+
+ it('includes the check when a policy with a null check gains a check expression', () => {
+ const payload = generateUpdatePolicyPayload(mockPolicy({ command: 'UPDATE' }), {
+ ...baseForm,
+ check: 'is_admin()',
+ })
+ expect(payload).toEqual({ check: 'is_admin()' })
+ })
+
+ it('includes the check when the check expression changed', () => {
+ const payload = generateUpdatePolicyPayload(
+ mockPolicy({ command: 'UPDATE', check: 'is_admin()' }),
+ { ...baseForm, check: 'is_owner()' }
+ )
+ expect(payload).toEqual({ check: 'is_owner()' })
+ })
+
+ it('omits the check when the check expression is unchanged or empty', () => {
+ const withCheck = mockPolicy({ command: 'UPDATE', check: 'is_admin()' })
+ expect(generateUpdatePolicyPayload(withCheck, { ...baseForm, check: ' is_admin()' })).toEqual(
+ {}
+ )
+ expect(generateUpdatePolicyPayload(withCheck, { ...baseForm, check: '' })).toEqual({})
+ })
+
+ it('maps the using editor to the check field for INSERT policies', () => {
+ const insertPolicy = mockPolicy({ command: 'INSERT', definition: null, check: null })
+ const payload = generateUpdatePolicyPayload(insertPolicy, { ...baseForm, using: 'true' })
+ expect(payload).toEqual({ check: 'true' })
+ })
+
+ it('never includes a definition for INSERT policies', () => {
+ const insertPolicy = mockPolicy({ command: 'INSERT', definition: null, check: 'true' })
+ const payload = generateUpdatePolicyPayload(insertPolicy, {
+ ...baseForm,
+ using: 'is_admin()',
+ check: 'ignored',
+ })
+ expect(payload).toEqual({ check: 'is_admin()' })
+ })
+
+ it('omits the check for INSERT policies when the expression is unchanged', () => {
+ const insertPolicy = mockPolicy({ command: 'INSERT', definition: null, check: 'true' })
+ expect(generateUpdatePolicyPayload(insertPolicy, { ...baseForm, using: ' true' })).toEqual({})
+ })
+
+ it('includes the name and roles when they changed', () => {
+ const payload = generateUpdatePolicyPayload(mockPolicy(), {
+ ...baseForm,
+ name: 'renamed_policy',
+ roles: ['anon', 'authenticated'],
+ })
+ expect(payload).toEqual({ name: 'renamed_policy', roles: ['anon', 'authenticated'] })
+ })
+})
diff --git a/apps/studio/components/interfaces/Database/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.ts b/apps/studio/components/interfaces/Database/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.ts
index f0341e8a06b..6e483e8a36f 100644
--- a/apps/studio/components/interfaces/Database/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.ts
+++ b/apps/studio/components/interfaces/Database/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.ts
@@ -1,5 +1,12 @@
import type { PGPolicy } from '@supabase/pg-meta'
-import { ident, keyword, safeSql, type SafeSqlFragment } from '@supabase/pg-meta/src/pg-format'
+import {
+ ident,
+ keyword,
+ safeSql,
+ untrustedSql,
+ type SafeSqlFragment,
+ type UntrustedSqlFragment,
+} from '@supabase/pg-meta/src/pg-format'
import { isEqual } from 'lodash'
// [Joshen] Not used but keeping this for now in case we do an inline editor
@@ -77,6 +84,55 @@ export const generateCreatePolicyQuery = ({
return safeSql`${withUsing};`
}
+/**
+ * Diffs the editor form against the stored policy and returns only the fields
+ * that changed — an empty result means there is nothing to save. A stored
+ * `null` definition/check (policy created without that clause) counts as
+ * empty, so typing an expression into a previously empty editor is a change.
+ * Empty form values never produce a payload field, because ALTER POLICY can
+ * only replace an expression, not remove it.
+ *
+ * Expressions are returned as UntrustedSqlFragment — the caller promotes them
+ * with acceptUntrustedSql in the submit handler.
+ */
+export const generateUpdatePolicyPayload = (
+ selectedPolicy: Pick<PGPolicy, 'name' | 'roles' | 'command' | 'definition' | 'check'>,
+ policyForm: {
+ name: string
+ roles: string[]
+ using?: string
+ check?: string
+ }
+): {
+ name?: string
+ roles?: string[]
+ definition?: UntrustedSqlFragment
+ check?: UntrustedSqlFragment
+} => {
+ const payload: {
+ name?: string
+ roles?: string[]
+ definition?: UntrustedSqlFragment
+ check?: UntrustedSqlFragment
+ } = {}
+ const usingVal = policyForm.using?.trim()
+ const checkVal = policyForm.check?.trim()
+
+ if (policyForm.name !== selectedPolicy.name) payload.name = policyForm.name
+ if (!isEqual(selectedPolicy.roles, policyForm.roles)) payload.roles = policyForm.roles
+
+ if (selectedPolicy.command === 'INSERT') {
+ // For INSERT policies editor one holds the with check expression
+ if (!!usingVal && usingVal !== selectedPolicy.check) payload.check = untrustedSql(usingVal)
+ } else {
+ if (!!usingVal && usingVal !== selectedPolicy.definition)
+ payload.definition = untrustedSql(usingVal)
+ if (!!checkVal && checkVal !== selectedPolicy.check) payload.check = untrustedSql(checkVal)
+ }
+
+ return payload
+}
+
export const checkIfPolicyHasChanged = (
selectedPolicy: PGPolicy,
policyForm: {
diff --git a/apps/studio/components/interfaces/Database/Policies/PolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Database/Policies/PolicyEditorPanel/index.tsx
index e24db3b4374..a7688b1fdae 100644
--- a/apps/studio/components/interfaces/Database/Policies/PolicyEditorPanel/index.tsx
+++ b/apps/studio/components/interfaces/Database/Policies/PolicyEditorPanel/index.tsx
@@ -12,7 +12,6 @@ import {
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common'
-import { isEqual } from 'lodash'
import { memo, useCallback, useEffect, useRef, useState } from 'react'
import { useForm, useWatch } from 'react-hook-form'
import { toast } from 'sonner'
@@ -35,7 +34,11 @@ import * as z from 'zod'
import { LockedCreateQuerySection, LockedRenameQuerySection } from './LockedQuerySection'
import { PolicyDetailsV2 } from './PolicyDetailsV2'
-import { checkIfPolicyHasChanged, generateCreatePolicyQuery } from './PolicyEditorPanel.utils'
+import {
+ checkIfPolicyHasChanged,
+ generateCreatePolicyQuery,
+ generateUpdatePolicyPayload,
+} from './PolicyEditorPanel.utils'
import { PolicyEditorPanelHeader } from './PolicyEditorPanelHeader'
import { PolicyTemplates } from './PolicyTemplates'
import { QueryError } from './QueryError'
@@ -172,12 +175,15 @@ export const PolicyEditorPanel = memo(function ({
name,
roles: roles.length === 0 ? ['public'] : roles.split(', '),
definition: editorOneFormattedValue,
- check: command === 'INSERT' ? editorOneFormattedValue : editorTwoFormattedValue,
+ check:
+ selectedPolicy.command === 'INSERT'
+ ? editorOneFormattedValue
+ : editorTwoFormattedValue,
})
: false
return policyCreateUnsaved || policyUpdateUnsaved
- }, [command, name, roles, selectedPolicy])
+ }, [name, roles, selectedPolicy])
const { confirmOnClose, handleOpenChange, modalProps } = useConfirmOnClose({
checkIsDirty: hasUnsavedChanges,
@@ -192,15 +198,14 @@ export const PolicyEditorPanel = memo(function ({
const usingExpr = command !== 'insert' ? using : undefined
const checkExpr = command === 'insert' ? using : check
- if (command === 'insert' && !checkExpr?.trim()) {
- return setFieldError('Please provide a SQL expression for the WITH CHECK statement')
- } else if (command !== 'insert' && !usingExpr?.trim()) {
- return setFieldError('Please provide a SQL expression for the USING statement')
- } else {
+ if (selectedPolicy === undefined) {
+ if (command === 'insert' && !checkExpr?.trim()) {
+ return setFieldError('Please provide a SQL expression for the WITH CHECK statement')
+ } else if (command !== 'insert' && !usingExpr?.trim()) {
+ return setFieldError('Please provide a SQL expression for the USING statement')
+ }
setFieldError(undefined)
- }
- if (selectedPolicy === undefined) {
const sql = generateCreatePolicyQuery({
name,
schema,
@@ -222,34 +227,37 @@ export const PolicyEditorPanel = memo(function ({
},
})
} else if (selectedProject !== undefined) {
- const payload: {
- name?: string
- definition?: SafeSqlFragment
- check?: SafeSqlFragment
- roles?: Array<string>
- } = {}
const updatedRoles = roles.length === 0 ? ['public'] : roles.split(', ')
- // Trim for string comparison against the stored policy values. The Save click is the
- // explicit user gesture that promotes editor content to executable SQL.
- const usingVal = using?.trim()
- const checkVal = check?.trim()
-
- if (name !== selectedPolicy.name) payload.name = name
- if (!isEqual(selectedPolicy.roles, updatedRoles)) payload.roles = updatedRoles
- if (selectedPolicy.definition !== null && selectedPolicy.definition !== usingVal)
- payload.definition =
- usingVal === undefined ? undefined : acceptUntrustedSql(untrustedSql(usingVal))
+ // A null definition/check is valid (the policy was created without that clause), so
+ // updates only require an expression where the policy already has one — ALTER POLICY
+ // can only replace an expression, not remove it.
if (selectedPolicy.command === 'INSERT') {
- // [Joshen] Cause editor one will be the check statement in this scenario
- if (selectedPolicy.check !== usingVal)
- payload.check =
- usingVal === undefined ? undefined : acceptUntrustedSql(untrustedSql(usingVal))
+ if (selectedPolicy.check !== null && !using?.trim()) {
+ return setFieldError(
+ 'The WITH CHECK expression cannot be removed. Provide a new expression, or delete and recreate the policy without it.'
+ )
+ }
} else {
- if (selectedPolicy.check !== checkVal)
- payload.check =
- checkVal === undefined ? undefined : acceptUntrustedSql(untrustedSql(checkVal))
+ if (selectedPolicy.definition !== null && !using?.trim()) {
+ return setFieldError(
+ 'The USING expression cannot be removed. Provide a new expression, or delete and recreate the policy without it.'
+ )
+ }
+ if (selectedPolicy.check !== null && !check?.trim()) {
+ return setFieldError(
+ 'The WITH CHECK expression cannot be removed. Provide a new expression, or delete and recreate the policy without it.'
+ )
+ }
}
+ setFieldError(undefined)
+
+ const payload = generateUpdatePolicyPayload(selectedPolicy, {
+ name,
+ roles: updatedRoles,
+ using,
+ check,
+ })
if (Object.keys(payload).length === 0) return onSelectCancel()
@@ -257,7 +265,15 @@ export const PolicyEditorPanel = memo(function ({
projectRef: selectedProject.ref,
connectionString: selectedProject?.connectionString,
originalPolicy: selectedPolicy,
- payload,
+ // The Save click is the explicit user gesture that promotes editor content
+ // to executable SQL.
+ payload: {
+ name: payload.name,
+ roles: payload.roles,
+ definition:
+ payload.definition === undefined ? undefined : acceptUntrustedSql(payload.definition),
+ check: payload.check === undefined ? undefined : acceptUntrustedSql(payload.check),
+ },
})
}
}