Skip to content

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

feat(studio): extend safe SQL model to policy editor and related interfaces (#45560)

Charis3f97eeea5a21
diff --git a/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx b/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx
index 279e153e1af..ecfe046f5d9 100644
--- a/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx
+++ b/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx
@@ -1,4 +1,10 @@
import { zodResolver } from '@hookform/resolvers/zod'
+import {
+ ident,
+ joinSqlFragments,
+ safeSql,
+ type SafeSqlFragment,
+} from '@supabase/pg-meta/src/pg-format'
import { useParams } from 'common'
import randomBytes from 'randombytes'
import { useEffect, useMemo } from 'react'
@@ -170,7 +176,7 @@ export const CreateHookSheet = ({
})
const statements = useMemo(() => {
- let permissionChanges: string[] = []
+ let permissionChanges: Array<SafeSqlFragment> = []
if (hook.method.type === 'postgres') {
if (
hook.method.schema !== '' &&
@@ -185,11 +191,16 @@ export const CreateHookSheet = ({
}
if (values.postgresValues.functionName !== '') {
+ const schema = values.postgresValues.schema
+ const functionName = values.postgresValues.functionName
permissionChanges = [
...permissionChanges,
- `-- Grant access to function to supabase_auth_admin\ngrant execute on function ${values.postgresValues.schema}.${values.postgresValues.functionName} to supabase_auth_admin;`,
- `-- Grant access to schema to supabase_auth_admin\ngrant usage on schema ${values.postgresValues.schema} to supabase_auth_admin;`,
- `-- Revoke function permissions from authenticated, anon and public\nrevoke execute on function ${values.postgresValues.schema}.${values.postgresValues.functionName} from authenticated, anon, public;`,
+ safeSql`-- Grant access to function to supabase_auth_admin
+grant execute on function ${ident(schema)}.${ident(functionName)} to supabase_auth_admin;`,
+ safeSql`-- Grant access to schema to supabase_auth_admin
+grant usage on schema ${ident(schema)} to supabase_auth_admin;`,
+ safeSql`-- Revoke function permissions from authenticated, anon and public
+revoke execute on function ${ident(schema)}.${ident(functionName)} from authenticated, anon, public;`,
]
}
return permissionChanges
@@ -202,7 +213,7 @@ export const CreateHookSheet = ({
executeSql({
projectRef,
connectionString: project!.connectionString,
- sql: statements.join('\n'),
+ sql: joinSqlFragments(statements, '\n'),
})
}
onClose()
diff --git a/apps/studio/components/interfaces/Auth/Hooks/HooksListing.tsx b/apps/studio/components/interfaces/Auth/Hooks/HooksListing.tsx
index c7a257207fe..5240577c525 100644
--- a/apps/studio/components/interfaces/Auth/Hooks/HooksListing.tsx
+++ b/apps/studio/components/interfaces/Auth/Hooks/HooksListing.tsx
@@ -1,3 +1,4 @@
+import { joinSqlFragments } from '@supabase/pg-meta/src/pg-format'
import { useParams } from 'common'
import { parseAsString, useQueryState } from 'nuqs'
import { useEffect, useState } from 'react'
@@ -50,7 +51,7 @@ export const HooksListing = () => {
await executeSql({
projectRef,
connectionString: project!.connectionString,
- sql: revokeStatements.join('\n'),
+ sql: joinSqlFragments(revokeStatements, '\n'),
})
}
toast.success(`${selectedHookForDeletion.title} has been deleted.`)
diff --git a/apps/studio/components/interfaces/Auth/Hooks/hooks.utils.ts b/apps/studio/components/interfaces/Auth/Hooks/hooks.utils.ts
index f77d58365ca..630d61ced8d 100644
--- a/apps/studio/components/interfaces/Auth/Hooks/hooks.utils.ts
+++ b/apps/studio/components/interfaces/Auth/Hooks/hooks.utils.ts
@@ -1,3 +1,5 @@
+import { ident, safeSql, type SafeSqlFragment } from '@supabase/pg-meta/src/pg-format'
+
import { Hook } from './hooks.constants'
export const extractMethod = (
@@ -34,10 +36,16 @@ export const isValidHook = (h: Hook) => {
* @param functionName the function name associated with the hook
* @returns an array of SQL statements to restore the original permissions to the function
*/
-export const getRevokePermissionStatements = (schema: string, functionName: string): string[] => {
+export const getRevokePermissionStatements = (
+ schema: string,
+ functionName: string
+): Array<SafeSqlFragment> => {
return [
- `-- Revoke access to function from supabase_auth_admin\nrevoke execute on function ${schema}.${functionName} from supabase_auth_admin;`,
- `-- Revoke access to schema from supabase_auth_admin\nrevoke usage on schema ${schema} from supabase_auth_admin;`,
- `-- Restore function permissions to authenticated, anon and public\ngrant execute on function ${schema}.${functionName} to authenticated, anon, public;`,
+ safeSql`-- Revoke access to function from supabase_auth_admin
+revoke execute on function ${ident(schema)}.${ident(functionName)} from supabase_auth_admin;`,
+ safeSql`-- Revoke access to schema from supabase_auth_admin
+revoke usage on schema ${ident(schema)} from supabase_auth_admin;`,
+ safeSql`-- Restore function permissions to authenticated, anon and public
+grant execute on function ${ident(schema)}.${ident(functionName)} to authenticated, anon, public;`,
]
}
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModal.constants.ts b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModal.constants.ts
index bd40f9d9ed2..9e918f6cc11 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModal.constants.ts
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModal.constants.ts
@@ -1,3 +1,5 @@
+import { safeSql } from '@supabase/pg-meta/src/pg-format'
+
import { PolicyTemplate } from '../PolicyTemplates/PolicyTemplates.constants'
/**
@@ -27,8 +29,8 @@ create policy "Enable read access for all users"
on "${schema}"."${table}"
for select using (true);`.trim(),
name: 'Enable read access for all users',
- definition: 'true',
- check: '',
+ definition: safeSql`true`,
+ check: safeSql``,
command: 'SELECT',
roles: [],
},
@@ -43,8 +45,8 @@ on "${schema}"."${table}"
for insert to authenticated
with check (true);`.trim(),
name: 'Enable insert for authenticated users only',
- definition: '',
- check: 'true',
+ definition: safeSql``,
+ check: safeSql`true`,
command: 'INSERT',
roles: ['authenticated'],
},
@@ -61,8 +63,8 @@ for delete using (
(select auth.uid()) = user_id
);`.trim(),
name: 'Enable delete for users based on user_id',
- definition: '(select auth.uid()) = user_id',
- check: '',
+ definition: safeSql`(select auth.uid()) = user_id`,
+ check: safeSql``,
command: 'DELETE',
roles: [],
},
@@ -79,8 +81,8 @@ for insert with check (
(select auth.uid()) = user_id
);`.trim(),
name: 'Enable insert for users based on user_id',
- definition: '',
- check: '(select auth.uid()) = user_id',
+ definition: safeSql``,
+ check: safeSql`(select auth.uid()) = user_id`,
command: 'INSERT',
roles: [],
},
@@ -101,8 +103,8 @@ on teams for update using (
)
);
`.trim(),
- definition: `(select auth.uid()) in (select user_id from members where team_id = id)`,
- check: '',
+ definition: safeSql`(select auth.uid()) in (select user_id from members where team_id = id)`,
+ check: safeSql``,
command: 'UPDATE',
roles: [],
},
@@ -127,8 +129,8 @@ for all using (
);
`.trim(),
name: 'Policy with security definer functions',
- definition: 'team_id in (select get_teams_for_user(auth.uid()))',
- check: '',
+ definition: safeSql`team_id in (select get_teams_for_user(auth.uid()))`,
+ check: safeSql``,
command: 'ALL',
roles: [],
},
@@ -148,8 +150,8 @@ for select using (
created_at > (current_timestamp - interval '1 day')
);
`.trim(),
- definition: `created_at > (current_timestamp - interval '1 day')`,
- check: '',
+ definition: safeSql`created_at > (current_timestamp - interval '1 day')`,
+ check: safeSql``,
command: 'SELECT',
roles: [],
},
@@ -167,8 +169,8 @@ using (
(select auth.uid()) = user_id
);`.trim(),
name: 'Enable users to view their own data only',
- definition: '(select auth.uid()) = user_id',
- check: '',
+ definition: safeSql`(select auth.uid()) = user_id`,
+ check: safeSql``,
command: 'SELECT',
roles: ['authenticated'],
},
@@ -187,8 +189,8 @@ on realtime.messages for select
to authenticated
using ( realtime.messages.extension = 'broadcast' );`.trim(),
name: 'Allow listening for broadcasts for authenticated users only',
- definition: "realtime.messages.extension = 'broadcast'",
- check: '',
+ definition: safeSql`realtime.messages.extension = 'broadcast'`,
+ check: safeSql``,
command: 'SELECT',
roles: ['authenticated'],
},
@@ -203,8 +205,8 @@ ON realtime.messages for insert
TO authenticated
with check ( realtime.messages.extension = 'broadcast' );`.trim(),
name: 'Allow pushing broadcasts for authenticated users only',
- definition: "realtime.messages.extension = 'broadcast'",
- check: "realtime.messages.extension = 'broadcast'",
+ definition: safeSql`realtime.messages.extension = 'broadcast'`,
+ check: safeSql`realtime.messages.extension = 'broadcast'`,
command: 'INSERT',
roles: ['authenticated'],
},
@@ -218,8 +220,8 @@ create policy "Allow listening for broadcasts from a specific channel"
on realtime.messages for select
using ( realtime.messages.extension = 'broadcast' AND realtime.topic() = 'channel_name' );`.trim(),
name: 'Allow listening for broadcasts from a specific channel',
- definition: `realtime.messages.extension = 'broadcast' AND realtime.topic() = 'channel_name'`,
- check: '',
+ definition: safeSql`realtime.messages.extension = 'broadcast' AND realtime.topic() = 'channel_name'`,
+ check: safeSql``,
command: 'SELECT',
roles: [],
},
@@ -233,8 +235,8 @@ create policy "Allow pushing broadcasts to specific channel"
ON realtime.messages for insert
with check ( realtime.messages.extension = 'broadcast' AND realtime.topic() = 'channel_name' );`.trim(),
name: 'Allow pushing broadcasts to specific channel',
- definition: `realtime.messages.extension = 'broadcast' AND realtime.topic() = 'channel_name'`,
- check: `realtime.messages.extension = 'broadcast' AND realtime.topic() = 'channel_name'`,
+ definition: safeSql`realtime.messages.extension = 'broadcast' AND realtime.topic() = 'channel_name'`,
+ check: safeSql`realtime.messages.extension = 'broadcast' AND realtime.topic() = 'channel_name'`,
command: 'INSERT',
roles: [],
},
@@ -250,8 +252,8 @@ on realtime.messages for select
to authenticated
using ( realtime.messages.extension = 'presence' );`.trim(),
name: 'Allow listening for presences on all channels for authenticated users only',
- definition: "realtime.messages.extension = 'presence'",
- check: '',
+ definition: safeSql`realtime.messages.extension = 'presence'`,
+ check: safeSql``,
command: 'SELECT',
roles: ['authenticated'],
},
@@ -268,8 +270,8 @@ TO authenticated
with check ( realtime.messages.extension = 'presence' );
;`.trim(),
name: 'Allow broadcasting presences on all channels for authenticated users only',
- definition: "realtime.messages.extension = 'presence'",
- check: "realtime.messages.extension = 'presence'",
+ definition: safeSql`realtime.messages.extension = 'presence'`,
+ check: safeSql`realtime.messages.extension = 'presence'`,
command: 'INSERT',
roles: ['authenticated'],
},
@@ -283,8 +285,8 @@ create policy "Allow listening for presences from a specific channel"
on realtime.messages for select
using ( realtime.messages.extension = 'presence' AND realtime.topic() = 'channel_name' );`.trim(),
name: 'Allow listening for presences from a specific channel',
- definition: `realtime.messages.extension = 'presence' AND realtime.topic() = 'channel_name'`,
- check: '',
+ definition: safeSql`realtime.messages.extension = 'presence' AND realtime.topic() = 'channel_name'`,
+ check: safeSql``,
command: 'SELECT',
roles: [],
},
@@ -299,8 +301,8 @@ ON realtime.messages for insert
with check ( realtime.messages.extension = 'presence' AND realtime.topic() = 'channel_name' );
;`.trim(),
name: 'Publish presence to a specific channel',
- definition: `realtime.messages.extension = 'presence' AND realtime.topic() = 'channel_name'`,
- check: `realtime.messages.extension = 'presence' AND realtime.topic() = 'channel_name'`,
+ definition: safeSql`realtime.messages.extension = 'presence' AND realtime.topic() = 'channel_name'`,
+ check: safeSql`realtime.messages.extension = 'presence' AND realtime.topic() = 'channel_name'`,
command: 'INSERT',
roles: [],
},
@@ -318,8 +320,8 @@ export const getQueuePolicyTemplates = (): PolicyTemplate[] => {
name: 'Allow anon and authenticated to access messages from queue',
description:
'Base policy to ensure that anon and authenticated can only access appropriate rows. USING and CHECK statements will need to be adjusted accordingly',
- definition: 'true',
- check: 'true',
+ definition: safeSql`true`,
+ check: safeSql`true`,
command: 'ALL',
roles: ['anon', 'authenticated'],
},
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyDetailsV2.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyDetailsV2.tsx
index 1de3817ad99..477095ce075 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyDetailsV2.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyDetailsV2.tsx
@@ -1,3 +1,9 @@
+import {
+ ident,
+ joinSqlFragments,
+ safeSql,
+ type SafeSqlFragment,
+} from '@supabase/pg-meta/src/pg-format'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { Check, ChevronsUpDown } from 'lucide-react'
import { useEffect, useState } from 'react'
@@ -55,6 +61,7 @@ interface PolicyDetailsV2Props {
roles: string
}>
onUpdateCommand: (command: string) => void
+ onRolesChange?: (fragment: SafeSqlFragment) => void
authContext: 'database' | 'realtime'
}
@@ -65,6 +72,7 @@ export const PolicyDetailsV2 = ({
isEditing,
form,
onUpdateCommand,
+ onRolesChange,
authContext,
}: PolicyDetailsV2Props) => {
const { data: project } = useSelectedProjectQuery()
@@ -309,7 +317,17 @@ export const PolicyDetailsV2 = ({
</FormLabel>
<FormControl>
<MultiSelector
- onValuesChange={(roles) => field.onChange(roles.join(', '))}
+ onValuesChange={(roles) => {
+ field.onChange(roles.join(', '))
+ onRolesChange?.(
+ roles.length === 0
+ ? safeSql`public`
+ : joinSqlFragments(
+ roles.map((r) => ident(r)),
+ ', '
+ )
+ )
+ }}
disabled={!canUpdatePolicies}
values={field.value.length === 0 ? [] : field.value?.split(', ')}
size="small"
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.ts b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.ts
index bd8b9c8cbd3..f4a77e9c52e 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.ts
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.ts
@@ -1,4 +1,4 @@
-import { ident } from '@supabase/pg-meta/src/pg-format'
+import { ident, keyword, safeSql, type SafeSqlFragment } from '@supabase/pg-meta/src/pg-format'
import type { PostgresPolicy } from '@supabase/postgres-meta'
import { isEqual } from 'lodash'
@@ -62,16 +62,19 @@ export const generateCreatePolicyQuery = ({
table: string
behavior: string
command: string
- roles: string
- using?: string
- check?: string
-}) => {
- const querySkeleton = `create policy ${ident(name)} on ${ident(schema)}.${ident(table)} as ${behavior} for ${command} to ${roles}`
- const query =
- command === 'insert'
- ? `${querySkeleton} with check (${check});`
- : `${querySkeleton} using (${using})${(check ?? '').length > 0 ? `with check (${check});` : ';'}`
- return query
+ roles: SafeSqlFragment
+ using?: SafeSqlFragment
+ check?: SafeSqlFragment
+}): SafeSqlFragment => {
+ const skeleton = safeSql`create policy ${ident(name)} on ${ident(schema)}.${ident(table)} as ${keyword(behavior)} for ${keyword(command)} to ${roles}`
+ if (command === 'insert') {
+ return safeSql`${skeleton} with check (${check ?? safeSql``});`
+ }
+ const withUsing = safeSql`${skeleton} using (${using ?? safeSql``})`
+ if ((check ?? '').length > 0) {
+ return safeSql`${withUsing} with check (${check ?? safeSql``});`
+ }
+ return safeSql`${withUsing};`
}
export const checkIfPolicyHasChanged = (
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/RLSCodeEditor.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/RLSCodeEditor.tsx
index 292236f3026..2d627604389 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/RLSCodeEditor.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/RLSCodeEditor.tsx
@@ -33,6 +33,7 @@ interface RLSCodeEditorProps {
export const RLSCodeEditor = ({
id,
defaultValue,
+ onInputChange,
wrapperClassName,
className,
value,
@@ -115,6 +116,7 @@ export const RLSCodeEditor = ({
}
onChange()
+ onInputChange?.(value)
}
// when the value has changed, trigger the onChange callback so that the height of the container can be adjusted.
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx
index 35b72af2f72..cedfe7f4d6c 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx
@@ -1,6 +1,14 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { Monaco } from '@monaco-editor/react'
-import type { PostgresPolicy } from '@supabase/postgres-meta'
+import {
+ acceptUntrustedSql,
+ ident,
+ joinSqlFragments,
+ safeSql,
+ untrustedSql,
+ type DisplayableSqlFragment,
+ type SafeSqlFragment,
+} from '@supabase/pg-meta/src/pg-format'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common'
@@ -32,6 +40,7 @@ import { PolicyEditorPanelHeader } from './PolicyEditorPanelHeader'
import { PolicyTemplates } from './PolicyTemplates'
import { QueryError } from './QueryError'
import { RLSCodeEditor } from './RLSCodeEditor'
+import type { Policy } from '@/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRow.utils'
import { IStandaloneCodeEditor } from '@/components/interfaces/SQLEditor/SQLEditor.types'
import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
@@ -41,13 +50,14 @@ import { QueryResponseError, useExecuteSqlMutation } from '@/data/sql/execute-sq
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'
+import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
interface PolicyEditorPanelProps {
visible: boolean
schema: string
searchString?: string
selectedTable?: string
- selectedPolicy?: PostgresPolicy
+ selectedPolicy?: Policy
onSelectCancel: () => void
authContext: 'database' | 'realtime'
}
@@ -90,8 +100,9 @@ export const PolicyEditorPanel = memo(function ({
)
// [Joshen] Hyrid form fields, just spit balling to get a decent POC out
- const [using, setUsing] = useState('')
- const [check, setCheck] = useState('')
+ const [using, setUsing] = useState<DisplayableSqlFragment | undefined>(undefined)
+ const [check, setCheck] = useState<DisplayableSqlFragment | undefined>(undefined)
+ const [rolesFragment, setRolesFragment] = useState<SafeSqlFragment>(safeSql`public`)
const [fieldError, setFieldError] = useState<string>()
const [showCheckBlock, setShowCheckBlock] = useState(true)
@@ -172,17 +183,15 @@ export const PolicyEditorPanel = memo(function ({
const onSubmit = (data: z.infer<typeof FormSchema>) => {
const { name, table, behavior, command, roles } = data
- let using = editorOneRef.current?.getValue().trim() ?? undefined
- let check = editorTwoRef.current?.getValue().trim()
- // [Terry] b/c editorOneRef will be the check statement in this scenario
- if (command === 'insert') {
- check = using
- }
+ // For INSERT: editor one holds the check expression (not using)
+ // For others: editor one = using, editor two = optional check
+ const usingExpr = command !== 'insert' ? using : undefined
+ const checkExpr = command === 'insert' ? using : check
- if (command === 'insert' && (check === undefined || check.length === 0)) {
+ if (command === 'insert' && !checkExpr?.trim()) {
return setFieldError('Please provide a SQL expression for the WITH CHECK statement')
- } else if (command !== 'insert' && (using === undefined || using.length === 0)) {
+ } else if (command !== 'insert' && !usingExpr?.trim()) {
return setFieldError('Please provide a SQL expression for the USING statement')
} else {
setFieldError(undefined)
@@ -190,14 +199,14 @@ export const PolicyEditorPanel = memo(function ({
if (selectedPolicy === undefined) {
const sql = generateCreatePolicyQuery({
- name: name,
+ name,
schema,
table,
behavior,
command,
- roles: roles.length === 0 ? 'public' : roles,
- using: using ?? '',
- check: command === 'insert' ? (using ?? '') : (check ?? ''),
+ roles: rolesFragment,
+ using: usingExpr ? acceptUntrustedSql(usingExpr) : undefined,
+ check: checkExpr ? acceptUntrustedSql(checkExpr) : undefined,
})
setError(undefined)
@@ -214,20 +223,23 @@ export const PolicyEditorPanel = memo(function ({
name?: string
definition?: string
check?: string
- roles?: string[]
+ roles?: Array<string>
} = {}
const updatedRoles = roles.length === 0 ? ['public'] : roles.split(', ')
+ // Trim for string comparison against the stored policy values
+ 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 !== using)
- payload.definition = using
+ if (selectedPolicy.definition !== null && selectedPolicy.definition !== usingVal)
+ payload.definition = usingVal
if (selectedPolicy.command === 'INSERT') {
- // [Joshen] Cause editorOneRef will be the check statement in this scenario
- if (selectedPolicy.check !== using) payload.check = using
+ // [Joshen] Cause editor one will be the check statement in this scenario
+ if (selectedPolicy.check !== usingVal) payload.check = usingVal
} else {
- if (selectedPolicy.check !== check) payload.check = check
+ if (selectedPolicy.check !== checkVal) payload.check = checkVal
}
if (Object.keys(payload).length === 0) return onSelectCancel()
@@ -241,8 +253,7 @@ export const PolicyEditorPanel = memo(function ({
}
}
- // when the panel is closed, reset all values
- useEffect(() => {
+ const resetState = useStaticEffectEvent(() => {
if (!visible) {
editorOneRef.current?.setValue('')
editorTwoRef.current?.setValue('')
@@ -251,8 +262,9 @@ export const PolicyEditorPanel = memo(function ({
setShowDetails(false)
setSelectedDiff(undefined)
- setUsing('')
- setCheck('')
+ setUsing(undefined)
+ setCheck(undefined)
+ setRolesFragment(safeSql`public`)
setShowCheckBlock(false)
setFieldError(undefined)
@@ -268,16 +280,30 @@ export const PolicyEditorPanel = memo(function ({
command: command.toLowerCase(),
roles: roles.length === 1 && roles[0] === 'public' ? '' : roles.join(', '),
})
- if (selectedPolicy.definition) setUsing(` ${selectedPolicy.definition}`)
- if (selectedPolicy.check) setCheck(` ${selectedPolicy.check}`)
+ if (selectedPolicy.definition) setUsing(safeSql` ${selectedPolicy.definition}`)
+ if (selectedPolicy.check && selectedPolicy.command === 'INSERT')
+ setUsing(safeSql` ${selectedPolicy.check}`)
+ if (selectedPolicy.check && selectedPolicy.command !== 'INSERT')
+ setCheck(safeSql` ${selectedPolicy.check}`)
if (selectedPolicy.check && selectedPolicy.command !== 'INSERT') {
setShowCheckBlock(true)
}
+ setRolesFragment(
+ roles.length === 1 && roles[0] === 'public'
+ ? safeSql`public`
+ : joinSqlFragments(
+ roles.map((r) => ident(r)),
+ ', '
+ )
+ )
} else if (selectedTable !== undefined) {
form.reset({ ...defaultValues, table: selectedTable })
}
}
- }, [visible])
+ })
+
+ // when the panel is closed, reset all values
+ useEffect(resetState, [visible, resetState])
// whenever the deps (current policy details, new error or error panel opens) change, recalculate
// the height of the editor
@@ -323,6 +349,7 @@ export const PolicyEditorPanel = memo(function ({
setShowCheckBlock(true)
}
}}
+ onRolesChange={(frag) => setRolesFragment(frag)}
authContext={authContext}
/>
<div className="h-full">
@@ -348,11 +375,12 @@ export const PolicyEditorPanel = memo(function ({
? '-- Provide a SQL expression for the with check statement'
: '-- Provide a SQL expression for the using statement'
}
- defaultValue={command === 'insert' ? check : using}
- value={command === 'insert' ? check : using}
+ defaultValue={using}
+ value={using}
editorRef={editorOneRef}
monacoRef={monacoOneRef as any}
lineNumberStart={6}
+ onInputChange={(value) => setUsing(untrustedSql(value ?? ''))}
onChange={() => {
setExpOneContentHeight(editorOneRef.current?.getContentHeight() ?? 0)
setExpOneLineCount(editorOneRef.current?.getModel()?.getLineCount() ?? 1)
@@ -412,6 +440,7 @@ export const PolicyEditorPanel = memo(function ({
editorRef={editorTwoRef}
monacoRef={monacoTwoRef as any}
lineNumberStart={7 + expOneLineCount}
+ onInputChange={(value) => setCheck(untrustedSql(value ?? ''))}
onChange={() => {
setExpTwoContentHeight(editorTwoRef.current?.getContentHeight() ?? 0)
setExpTwoLineCount(
@@ -548,8 +577,17 @@ export const PolicyEditorPanel = memo(function ({
form.setValue('command', value.command.toLowerCase())
form.setValue('roles', value.roles.join(', ') ?? '')
- setUsing(` ${value.definition}`)
- setCheck(` ${value.check}`)
+ setUsing(safeSql` ${value.definition}`)
+ setCheck(safeSql` ${value.check}`)
+ setRolesFragment(
+ value.roles.length === 0 ||
+ (value.roles.length === 1 && value.roles[0] === 'public')
+ ? safeSql`public`
+ : joinSqlFragments(
+ value.roles.map((r: string) => ident(r)),
+ ', '
+ )
+ )
setExpOneLineCount(1)
setExpTwoLineCount(1)
setFieldError(undefined)
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTemplates/PolicyTemplates.constants.ts b/apps/studio/components/interfaces/Auth/Policies/PolicyTemplates/PolicyTemplates.constants.ts
index eba327053d1..19fe1d66272 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTemplates/PolicyTemplates.constants.ts
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTemplates/PolicyTemplates.constants.ts
@@ -1,3 +1,5 @@
+import type { SafeSqlFragment } from '@supabase/pg-meta/src/pg-format'
+
export interface PolicyTemplate {
id: string
preview: boolean
@@ -5,8 +7,8 @@ export interface PolicyTemplate {
description: string
name: string
statement: string
- definition: string
- check: string
+ definition: SafeSqlFragment
+ check: SafeSqlFragment
command: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | 'ALL'
- roles: string[]
+ roles: Array<string>
}
diff --git a/apps/studio/components/interfaces/Docs/Description.tsx b/apps/studio/components/interfaces/Docs/Description.tsx
index d39b0e860dc..89feaa463a1 100644
--- a/apps/studio/components/interfaces/Docs/Description.tsx
+++ b/apps/studio/components/interfaces/Docs/Description.tsx
@@ -1,3 +1,4 @@
+import { ident, literal, safeSql } from '@supabase/pg-meta/src/pg-format'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { noop } from 'lodash'
import { Loader } from 'lucide-react'
@@ -51,12 +52,12 @@ const Description = ({ content, metadata, onChange = noop }: DescrptionProps) =>
if (isUpdating || !canUpdateDescription) return false
setIsUpdating(true)
- let query = ''
- let description = value.replaceAll("'", "''")
+ let query: string | undefined
if (table && column)
- query = `comment on column public."${table}"."${column}" is '${description}';`
- if (table && !column) query = `comment on table public."${table}" is '${description}';`
- if (rpc) query = `comment on function "${rpc}" is '${description}';`
+ query = safeSql`comment on column ${ident('public')}.${ident(table)}.${ident(column)} is ${literal(value)};`
+ if (table && !column)
+ query = safeSql`comment on table ${ident('public')}.${ident(table)} is ${literal(value)};`
+ if (rpc) query = safeSql`comment on function ${ident(rpc)} is ${literal(value)};`
if (query) {
try {
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.tsx
index bf17a0c38d4..2b7c65a63d1 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.tsx
@@ -193,8 +193,7 @@ export const CreateCronJobSheet = ({ open, selectedCronJob, onClose }: CreateCro
}
}
- const command = `$$${values.snippet}$$`
- const query = buildCronQuery(name, schedule, command)
+ const query = buildCronQuery(name, schedule, values.snippet)
upsertCronJob(
{
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.tsx
index a35ce42d43f..cc782d50837 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.tsx
@@ -1,3 +1,4 @@
+import { keyword, literal, safeSql, type SafeSqlFragment } from '@supabase/pg-meta/src/pg-format'
import { toString as CronToString } from 'cronstrue'
import { Column } from 'react-data-grid'
import { cn } from 'ui'
@@ -7,12 +8,10 @@ import { CRON_TABLE_COLUMNS, HTTPHeader, secondsPattern } from './CronJobs.const
import { CronJobTableCell } from './CronJobTableCell'
import { CronJob } from '@/data/database-cron-jobs/database-cron-jobs-infinite-query'
-const escapeSqlLiteral = (value = '') => value.replaceAll("'", "''")
const unescapeSqlLiteral = (value = '') => value.replaceAll("''", "'")
-export function buildCronQuery(name: string, schedule: string, command: string) {
- const escapedName = escapeSqlLiteral(name)
- return `select cron.schedule('${escapedName}', '${schedule}', ${command});`
+export function buildCronQuery(name: string, schedule: string, command: string): SafeSqlFragment {
+ return safeSql`select cron.schedule(${literal(name)}, ${literal(schedule)}, ${literal(command)});`
}
export const buildHttpRequestCommand = (
@@ -21,18 +20,18 @@ export const buildHttpRequestCommand = (
headers: HTTPHeader[] = [],
body: string | undefined,
timeout: number
-) => {
- return `
+): SafeSqlFragment => {
+ const funcName = keyword(method === 'GET' ? 'http_get' : 'http_post')
+ const headersJson = JSON.stringify(
+ Object.fromEntries(headers.filter((v) => v.name && v.value).map((v) => [v.name, v.value]))
+ )
+ const bodyPart = method === 'POST' && body ? safeSql`\n body:=${literal(body)},` : safeSql``
+ return safeSql`
select
- net.${method === 'GET' ? 'http_get' : 'http_post'}(
- url:='${escapeSqlLiteral(url)}',
- headers:=jsonb_build_object(${headers
- .filter((v) => v.name && v.value)
- .map((v) => `'${escapeSqlLiteral(v.name)}', '${escapeSqlLiteral(v.value)}'`)
- .join(
- ', '
- )}), ${method === 'POST' && body ? `\n body:='${escapeSqlLiteral(body)}',` : ''}
- timeout_milliseconds:=${timeout}
+ net.${funcName}(
+ url:=${literal(url)},
+ headers:=${literal(headersJson)}::jsonb, ${bodyPart}
+ timeout_milliseconds:=${literal(timeout)}
);`
}
diff --git a/apps/studio/components/interfaces/Linter/GraphqlExposureLintCTA.tsx b/apps/studio/components/interfaces/Linter/GraphqlExposureLintCTA.tsx
index 85cf2b4374e..1ebfa4f80a4 100644
--- a/apps/studio/components/interfaces/Linter/GraphqlExposureLintCTA.tsx
+++ b/apps/studio/components/interfaces/Linter/GraphqlExposureLintCTA.tsx
@@ -1,3 +1,4 @@
+import { ident, safeSql } from '@supabase/pg-meta/src/pg-format'
import { useQueryClient } from '@tanstack/react-query'
import { EyeOff, Lock } from 'lucide-react'
import { useState } from 'react'
@@ -26,8 +27,6 @@ export const asGraphqlExposureLint = (
? (name as GraphqlExposureLintName)
: null
-const quoteIdent = (ident: string) => `"${ident.replace(/"/g, '""')}"`
-
interface GraphqlExposureLintCTAProps {
lintName: GraphqlExposureLintName
projectRef: string
@@ -68,9 +67,10 @@ export const GraphqlExposureLintCTA = ({
const audience = AUDIENCE[lintName]
const canAct = !!schema && !!name
- const revokeSql = canAct
- ? `revoke all on ${quoteIdent(schema)}.${quoteIdent(name)} from ${role};`
- : ''
+ const revokeSql =
+ schema && name
+ ? safeSql`revoke all on ${ident(schema)}.${ident(name)} from ${ident(role)};`
+ : undefined
const { mutate: executeSql, isPending: isRevoking } = useExecuteSqlMutation({
onSuccess: async () => {
@@ -87,7 +87,7 @@ export const GraphqlExposureLintCTA = ({
})
const handleRevoke = () => {
- if (!canAct) return
+ if (!revokeSql) return
executeSql({
projectRef,
connectionString: project?.connectionString,
diff --git a/apps/studio/components/interfaces/Realtime/Policies.tsx b/apps/studio/components/interfaces/Realtime/Policies.tsx
index d2cc296d583..770504521e3 100644
--- a/apps/studio/components/interfaces/Realtime/Policies.tsx
+++ b/apps/studio/components/interfaces/Realtime/Policies.tsx
@@ -1,10 +1,10 @@
-import { PostgresPolicy } from '@supabase/postgres-meta'
import { useMemo, useState } from 'react'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import { Policies } from '@/components/interfaces/Auth/Policies/Policies'
import { PoliciesDataProvider } from '@/components/interfaces/Auth/Policies/PoliciesDataContext'
import { PolicyEditorPanel } from '@/components/interfaces/Auth/Policies/PolicyEditorPanel'
+import type { Policy } from '@/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRow.utils'
import AlertError from '@/components/ui/AlertError'
import { useDatabasePoliciesQuery } from '@/data/database-policies/database-policies-query'
import { useTablesQuery } from '@/data/tables/tables-query'
@@ -14,7 +14,7 @@ export const RealtimePolicies = () => {
const { data: project } = useSelectedProjectQuery()
const [showPolicyEditor, setShowPolicyEditor] = useState(false)
- const [selectedPolicyToEdit, setSelectedPolicyToEdit] = useState<PostgresPolicy>()
+ const [selectedPolicyToEdit, setSelectedPolicyToEdit] = useState<Policy>()
const {
data: tables,
diff --git a/apps/studio/components/interfaces/Storage/PublicBucketWarning.tsx b/apps/studio/components/interfaces/Storage/PublicBucketWarning.tsx
index 6a96266217e..5204bb9262e 100644
--- a/apps/studio/components/interfaces/Storage/PublicBucketWarning.tsx
+++ b/apps/studio/components/interfaces/Storage/PublicBucketWarning.tsx
@@ -1,4 +1,4 @@
-import { ident } from '@supabase/pg-meta/src/pg-format'
+import { ident, safeSql } from '@supabase/pg-meta/src/pg-format'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { LOCAL_STORAGE_KEYS } from 'common'
import { useEffect, useState, type ReactNode } from 'react'
@@ -38,7 +38,7 @@ function persistDismiss(projectRef: string, bucketId: string): void {
}
function generatePolicyRemovalSql(policyName: string) {
- return `DROP POLICY IF EXISTS ${ident(policyName)} ON storage.objects;`
+ return safeSql`DROP POLICY IF EXISTS ${ident(policyName)} ON storage.objects;`
}
export interface PublicBucketWarningProps {
diff --git a/apps/studio/components/interfaces/TableGridEditor/ViewEntityAutofixSecurityModal.tsx b/apps/studio/components/interfaces/TableGridEditor/ViewEntityAutofixSecurityModal.tsx
index 39ce5efe34c..de88b180e9b 100644
--- a/apps/studio/components/interfaces/TableGridEditor/ViewEntityAutofixSecurityModal.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/ViewEntityAutofixSecurityModal.tsx
@@ -1,3 +1,4 @@
+import { ident, safeSql } from '@supabase/pg-meta/src/pg-format'
import { useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { ScrollArea } from 'ui'
@@ -51,9 +52,7 @@ export const ViewEntityAutofixSecurityModal = ({
})
function handleConfirm() {
- const sql = `
- ALTER VIEW "${table.schema}"."${table.name}" SET (security_invoker = on);
- `
+ const sql = safeSql`ALTER VIEW ${ident(table.schema)}.${ident(table.name)} SET (security_invoker = on);`
execute({
projectRef: project?.ref,
connectionString: project?.connectionString,
diff --git a/apps/studio/data/api-settings/create-and-expose-api-schema-mutation.ts b/apps/studio/data/api-settings/create-and-expose-api-schema-mutation.ts
index 55463395d70..152e642478f 100644
--- a/apps/studio/data/api-settings/create-and-expose-api-schema-mutation.ts
+++ b/apps/studio/data/api-settings/create-and-expose-api-schema-mutation.ts
@@ -1,3 +1,4 @@
+import { safeSql } from '@supabase/pg-meta/src/pg-format'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { components } from 'api-types'
import { toast } from 'sonner'
@@ -26,10 +27,8 @@ export async function createAndExposeApiSchema({
connectionString,
existingPostgrestConfig,
}: CreateAndExposeAPISchemaVariables) {
- const sql = `
-create schema if not exists api;
-grant usage on schema api to anon, authenticated;
- `.trim()
+ const sql = safeSql`create schema if not exists api;
+grant usage on schema api to anon, authenticated;`
await executeSql({ projectRef, connectionString, sql })
diff --git a/apps/studio/data/database-event-triggers/database-event-trigger-delete-mutation.ts b/apps/studio/data/database-event-triggers/database-event-trigger-delete-mutation.ts
index 7fd3fae7f4c..afca6166049 100644
--- a/apps/studio/data/database-event-triggers/database-event-trigger-delete-mutation.ts
+++ b/apps/studio/data/database-event-triggers/database-event-trigger-delete-mutation.ts
@@ -1,3 +1,4 @@
+import { ident, safeSql } from '@supabase/pg-meta/src/pg-format'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
@@ -6,8 +7,6 @@ import { databaseEventTriggerKeys } from './keys'
import { executeSql } from '@/data/sql/execute-sql-query'
import type { ResponseError, UseCustomMutationOptions } from '@/types'
-const escapeIdentifier = (value: string) => value.replace(/"/g, '""')
-
export type DatabaseEventTriggerDeleteVariables = {
trigger: DatabaseEventTrigger
projectRef: string
@@ -19,7 +18,7 @@ export async function deleteDatabaseEventTrigger({
projectRef,
connectionString,
}: DatabaseEventTriggerDeleteVariables) {
- const sql = `DROP EVENT TRIGGER IF EXISTS "${escapeIdentifier(trigger.name)}";`
+ const sql = safeSql`DROP EVENT TRIGGER IF EXISTS ${ident(trigger.name)};`
const { result } = await executeSql({
projectRef,
diff --git a/apps/studio/data/database-queues/database-queues-query.ts b/apps/studio/data/database-queues/database-queues-query.ts
index 5360e28a989..f6e7d683691 100644
--- a/apps/studio/data/database-queues/database-queues-query.ts
+++ b/apps/studio/data/database-queues/database-queues-query.ts
@@ -1,3 +1,4 @@
+import { safeSql } from '@supabase/pg-meta/src/pg-format'
import { useQuery } from '@tanstack/react-query'
import { databaseQueuesKeys } from './keys'
@@ -16,7 +17,7 @@ export type PostgresQueue = {
created_at: string
}
-const queueSqlQuery = `select * from pgmq.list_queues();`
+const queueSqlQuery = safeSql`select * from pgmq.list_queues();`
export async function getDatabaseQueues({ projectRef, connectionString }: DatabaseQueuesVariables) {
if (!projectRef) throw new Error('Project ref is required')
diff --git a/apps/studio/state/role-impersonation-state.tsx b/apps/studio/state/role-impersonation-state.tsx
index 67e48395435..b7e422519a0 100644
--- a/apps/studio/state/role-impersonation-state.tsx
+++ b/apps/studio/state/role-impersonation-state.tsx
@@ -1,3 +1,4 @@
+import { ident, literal, safeSql } from '@supabase/pg-meta/src/pg-format'
import { useConstant } from 'common'
import { createContext, PropsWithChildren, useCallback, useContext, useEffect } from 'react'
import { proxy, snapshot, subscribe, useSnapshot } from 'valtio'
@@ -73,7 +74,7 @@ export const RoleImpersonationStateContextProvider = ({ children }: PropsWithChi
const result = await executeSql({
projectRef: project?.ref,
connectionString: project?.connectionString,
- sql: `select ${schema}.${functionName}('${JSON.stringify(event)}'::jsonb) as event;`,
+ sql: safeSql`select ${ident(schema)}.${ident(functionName)}(${literal(JSON.stringify(event))}::jsonb) as event;`,
queryKey: ['customize-access-token', project?.ref],
})