Skip to content

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

studio,pg-meta: SafeSql for functions/policies/triggers (3/7) (#45990)

Charise9253854155a
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx
index 320d075bf81..8f35b023f72 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx
@@ -80,8 +80,6 @@ const defaultValues = {
/**
* Using memo for this component because everything rerenders on window focus because of outside fetches
- * Note: For INSERT command, editor one holds the check expression (not using)
- Whereas for others: editor one = using, editor two = optional check
*/
export const PolicyEditorPanel = memo(function ({
visible,
@@ -186,7 +184,8 @@ export const PolicyEditorPanel = memo(function ({
const onSubmit = (data: z.infer<typeof FormSchema>) => {
const { name, table, behavior, command, roles } = data
- // [Joshen] Refer to top note as to why we're using the "USING" section for INSERT
+ // 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
@@ -222,25 +221,31 @@ export const PolicyEditorPanel = memo(function ({
} else if (selectedProject !== undefined) {
const payload: {
name?: string
- definition?: string
- check?: 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
+ // 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
+ payload.definition =
+ usingVal === undefined ? undefined : acceptUntrustedSql(untrustedSql(usingVal))
if (selectedPolicy.command === 'INSERT') {
// [Joshen] Cause editor one will be the check statement in this scenario
- if (selectedPolicy.check !== usingVal) payload.check = usingVal
+ if (selectedPolicy.check !== usingVal)
+ payload.check =
+ usingVal === undefined ? undefined : acceptUntrustedSql(untrustedSql(usingVal))
} else {
- if (selectedPolicy.check !== checkVal) payload.check = checkVal
+ if (selectedPolicy.check !== checkVal)
+ payload.check =
+ checkVal === undefined ? undefined : acceptUntrustedSql(untrustedSql(checkVal))
}
if (Object.keys(payload).length === 0) return onSelectCancel()
@@ -281,19 +286,13 @@ export const PolicyEditorPanel = memo(function ({
command: command.toLowerCase(),
roles: roles.length === 1 && roles[0] === 'public' ? '' : roles.join(', '),
})
-
- // [Joshen] Refer to top note as to why we're using the "USING" section for INSERT
- if (selectedPolicy.definition) {
- setUsing(safeSql` ${selectedPolicy.definition}`)
- }
- if (selectedPolicy.check) {
- if (selectedPolicy.command === 'INSERT') setUsing(safeSql` ${selectedPolicy.check}`)
- else {
- setCheck(safeSql` ${selectedPolicy.check}`)
- setShowCheckBlock(true)
- }
+ 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}`)
+ setShowCheckBlock(true)
}
-
setRolesFragment(
roles.length === 1 && roles[0] === 'public'
? safeSql`public`
@@ -585,8 +584,6 @@ export const PolicyEditorPanel = memo(function ({
form.setValue('roles', value.roles.join(', ') ?? '')
setUsing(safeSql` ${value.definition}`)
-
- // [Joshen] Refer to top note as to why we're using the "USING" section for INSERT
if (value.check) {
if (value.command === 'INSERT') {
setUsing(safeSql` ${value.check}`)
@@ -594,7 +591,6 @@ export const PolicyEditorPanel = memo(function ({
setCheck(safeSql` ${value.check}`)
}
}
-
setRolesFragment(
value.roles.length === 0 ||
(value.roles.length === 1 && value.roles[0] === 'public')
diff --git a/apps/studio/components/interfaces/Database/Functions/CreateFunction/index.tsx b/apps/studio/components/interfaces/Database/Functions/CreateFunction/index.tsx
index 5bd889c6eaa..2f9944b22a2 100644
--- a/apps/studio/components/interfaces/Database/Functions/CreateFunction/index.tsx
+++ b/apps/studio/components/interfaces/Database/Functions/CreateFunction/index.tsx
@@ -1,4 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
+import { acceptUntrustedSql, untrustedSql } from '@supabase/pg-meta/src/pg-format'
import { isEmpty, isNull, keyBy, mapValues, partition } from 'lodash'
import { Plus, Trash } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
@@ -42,7 +43,7 @@ import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialo
import SchemaSelector from '@/components/ui/SchemaSelector'
import { useDatabaseExtensionsQuery } from '@/data/database-extensions/database-extensions-query'
import { useDatabaseFunctionCreateMutation } from '@/data/database-functions/database-functions-create-mutation'
-import { DatabaseFunction } from '@/data/database-functions/database-functions-query'
+import type { SavedDatabaseFunction } from '@/data/database-functions/database-functions-query'
import { useDatabaseFunctionUpdateMutation } from '@/data/database-functions/database-functions-update-mutation'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'
@@ -52,7 +53,7 @@ import type { FormSchema } from '@/types'
const FORM_ID = 'create-function-sidepanel'
interface CreateFunctionProps {
- func?: DatabaseFunction
+ func?: SavedDatabaseFunction
isDuplicating?: boolean
visible: boolean
onClose: () => void
@@ -101,10 +102,15 @@ export const CreateFunction = ({
const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (data) => {
if (!project) return console.error('Project is required')
+ // Submit click is the explicit user gesture that promotes form-entered SQL fragments
+ // (`args` items, `return_type`, and each `config_params` value) to executable.
const payload = {
...data,
- args: data.args.map((x) => `${x.name} ${x.type}`),
- config_params: mapValues(keyBy(data.config_params, 'name'), 'value') as Record<string, never>,
+ args: data.args.map((x) => acceptUntrustedSql(untrustedSql(`${x.name} ${x.type}`))),
+ return_type: acceptUntrustedSql(untrustedSql(data.return_type)),
+ config_params: mapValues(keyBy(data.config_params, 'name'), (item) =>
+ acceptUntrustedSql(untrustedSql(item.value))
+ ),
}
if (isEditing) {
diff --git a/apps/studio/data/database-functions/database-functions-create-mutation.ts b/apps/studio/data/database-functions/database-functions-create-mutation.ts
index 21a99b13b4d..cbebad502a8 100644
--- a/apps/studio/data/database-functions/database-functions-create-mutation.ts
+++ b/apps/studio/data/database-functions/database-functions-create-mutation.ts
@@ -1,4 +1,5 @@
import pgMeta from '@supabase/pg-meta'
+import type { PGFunctionCreate } from '@supabase/pg-meta/src/pg-meta-functions'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { z } from 'zod'
@@ -10,7 +11,7 @@ import type { ResponseError, UseCustomMutationOptions } from '@/types'
export type DatabaseFunctionCreateVariables = {
projectRef: string
connectionString?: string | null
- payload: z.infer<typeof pgMeta.functions.pgFunctionCreateZod>
+ payload: PGFunctionCreate
}
export async function createDatabaseFunction({
diff --git a/apps/studio/data/database-functions/database-functions-delete-mutation.ts b/apps/studio/data/database-functions/database-functions-delete-mutation.ts
index fb0929d5f32..dd2e4116adf 100644
--- a/apps/studio/data/database-functions/database-functions-delete-mutation.ts
+++ b/apps/studio/data/database-functions/database-functions-delete-mutation.ts
@@ -3,7 +3,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { z } from 'zod'
-import { DatabaseFunction } from './database-functions-query'
+import { SavedDatabaseFunction } from './database-functions-query'
import { databaseKeys } from '@/data/database/keys'
import { executeSql } from '@/data/sql/execute-sql-query'
import type { ResponseError, UseCustomMutationOptions } from '@/types'
@@ -11,7 +11,7 @@ import type { ResponseError, UseCustomMutationOptions } from '@/types'
export type DatabaseFunctionDeleteVariables = {
projectRef: string
connectionString?: string | null
- func: DatabaseFunction
+ func: SavedDatabaseFunction
}
export async function deleteDatabaseFunction({
diff --git a/apps/studio/data/database-functions/database-functions-query.ts b/apps/studio/data/database-functions/database-functions-query.ts
index 73686ddac88..aaf05eebd42 100644
--- a/apps/studio/data/database-functions/database-functions-query.ts
+++ b/apps/studio/data/database-functions/database-functions-query.ts
@@ -12,8 +12,19 @@ export type DatabaseFunctionsVariables = {
}
export type DatabaseFunction = z.infer<typeof pgMeta.functions.pgFunctionZod>
-export type SavedDatabaseFunction = Omit<DatabaseFunction, 'complete_statement'> & {
+export type SavedDatabaseFunction = Omit<
+ DatabaseFunction,
+ | 'complete_statement'
+ | 'argument_types'
+ | 'identity_argument_types'
+ | 'return_type'
+ | 'config_params'
+> & {
complete_statement: SafeSqlFragment
+ argument_types: SafeSqlFragment
+ identity_argument_types: SafeSqlFragment
+ return_type: SafeSqlFragment
+ config_params: Record<string, SafeSqlFragment> | null
}
const pgMetaFunctionsList = pgMeta.functions.list()
diff --git a/apps/studio/data/database-functions/database-functions-update-mutation.ts b/apps/studio/data/database-functions/database-functions-update-mutation.ts
index ced03309ec3..4b39c14db07 100644
--- a/apps/studio/data/database-functions/database-functions-update-mutation.ts
+++ b/apps/studio/data/database-functions/database-functions-update-mutation.ts
@@ -1,9 +1,10 @@
import pgMeta from '@supabase/pg-meta'
+import type { PGFunctionCreate } from '@supabase/pg-meta/src/pg-meta-functions'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { z } from 'zod'
-import type { DatabaseFunction } from './database-functions-query'
+import type { SavedDatabaseFunction } from './database-functions-query'
import { databaseKeys } from '@/data/database/keys'
import { executeSql } from '@/data/sql/execute-sql-query'
import type { ResponseError, UseCustomMutationOptions } from '@/types'
@@ -11,8 +12,8 @@ import type { ResponseError, UseCustomMutationOptions } from '@/types'
export type DatabaseFunctionUpdateVariables = {
projectRef: string
connectionString?: string | null
- func: DatabaseFunction
- payload: z.infer<typeof pgMeta.functions.pgFunctionCreateZod>
+ func: SavedDatabaseFunction
+ payload: PGFunctionCreate
}
export async function updateDatabaseFunction({
diff --git a/apps/studio/data/database-policies/database-policy-create-mutation.ts b/apps/studio/data/database-policies/database-policy-create-mutation.ts
index 36383fea2e5..0932f7a9db5 100644
--- a/apps/studio/data/database-policies/database-policy-create-mutation.ts
+++ b/apps/studio/data/database-policies/database-policy-create-mutation.ts
@@ -1,4 +1,5 @@
import pgMeta from '@supabase/pg-meta'
+import type { SafeSqlFragment } from '@supabase/pg-meta'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
@@ -10,8 +11,8 @@ export type CreatePolicyBody = {
name: string
table: string
schema?: string
- definition?: string
- check?: string
+ definition?: SafeSqlFragment
+ check?: SafeSqlFragment
action?: 'PERMISSIVE' | 'RESTRICTIVE'
command?: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | 'ALL'
roles?: string[]
diff --git a/apps/studio/data/database-policies/database-policy-update-mutation.ts b/apps/studio/data/database-policies/database-policy-update-mutation.ts
index ed2d893022d..db180c5f13b 100644
--- a/apps/studio/data/database-policies/database-policy-update-mutation.ts
+++ b/apps/studio/data/database-policies/database-policy-update-mutation.ts
@@ -1,4 +1,5 @@
import pgMeta from '@supabase/pg-meta'
+import type { SafeSqlFragment } from '@supabase/pg-meta'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
@@ -17,8 +18,8 @@ export type DatabasePolicyUpdateVariables = {
}
payload: {
name?: string
- definition?: string
- check?: string
+ definition?: SafeSqlFragment
+ check?: SafeSqlFragment
roles?: string[]
}
}
diff --git a/packages/pg-meta/src/pg-meta-functions.ts b/packages/pg-meta/src/pg-meta-functions.ts
index 886702ccd75..720991d349d 100644
--- a/packages/pg-meta/src/pg-meta-functions.ts
+++ b/packages/pg-meta/src/pg-meta-functions.ts
@@ -2,7 +2,14 @@ import { z } from 'zod'
import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
import { filterByList } from './helpers'
-import { ident, joinSqlFragments, literal, safeSql, type SafeSqlFragment } from './pg-format'
+import {
+ ident,
+ joinSqlFragments,
+ keyword,
+ literal,
+ safeSql,
+ type SafeSqlFragment,
+} from './pg-format'
import { FUNCTIONS_SQL } from './sql/functions'
export const pgFunctionZod = z.object({
@@ -176,7 +183,53 @@ export const pgFunctionCreateZod = z.object({
security_definer: z.boolean().optional(),
})
-export type PGFunctionCreate = z.infer<typeof pgFunctionCreateZod>
+// Zod validates `args`, `return_type`, and `config_params` values as runtime
+// strings; the SafeSqlFragment brand is a separate compile-time trust check.
+// `args` items are `"name type"` fragments, `return_type` is a type
+// expression (e.g. "integer", "SETOF users"), and each `config_params` value
+// is interpolated raw after `SET <param> TO` — all three drop into the
+// CREATE FUNCTION statement uninspected, so callers must promote untrusted
+// input via acceptUntrustedSql (and ensure the promotion satisfies safety
+// requirements) before calling create(). `'FROM CURRENT'` is a sentinel for
+// the `SET <param> FROM CURRENT` grammar and is detected by string equality.
+export type PGFunctionCreate = Omit<
+ z.infer<typeof pgFunctionCreateZod>,
+ 'args' | 'return_type' | 'config_params'
+> & {
+ args?: Array<SafeSqlFragment>
+ return_type?: SafeSqlFragment
+ config_params?: Record<string, SafeSqlFragment | 'FROM CURRENT'>
+}
+
+// `update()` and `remove()` reuse signature pieces from a previously-fetched
+// function. Callers must pass a value whose raw-SQL fields (`argument_types`,
+// `identity_argument_types`, `return_type`, and `config_params` values)
+// have been branded at the API/database boundary.
+export type PGSavedFunction = Omit<
+ PGFunction,
+ 'argument_types' | 'identity_argument_types' | 'return_type' | 'config_params'
+> & {
+ argument_types: SafeSqlFragment
+ identity_argument_types: SafeSqlFragment
+ return_type: SafeSqlFragment
+ config_params: Record<string, SafeSqlFragment> | null
+}
+
+// PostgreSQL configuration parameters can be namespaced custom GUCs
+// (e.g. `app.jwt_secret`, `pgaudit.log`). Neither `keyword` nor `ident`
+// fits: `keyword`'s regex rejects `.`, and `ident` would quote the whole
+// value as a single identifier (`"app.jwt_secret"`), which Postgres reads
+// as one literal name rather than a qualified reference. Split on `.`,
+// `ident` each segment, and rejoin with a literal `.`.
+function qualifiedIdent(value: string): SafeSqlFragment {
+ return value
+ .split('.')
+ .map(ident)
+ .reduce<SafeSqlFragment>(
+ (acc, part, i) => (i === 0 ? part : safeSql`${acc}.${part}`),
+ safeSql``
+ )
+}
function _generateCreateFunctionSql(
{
@@ -191,27 +244,29 @@ function _generateCreateFunctionSql(
config_params,
}: PGFunctionCreate,
{ replace = false } = {}
-): string {
- return /* SQL */ `
- CREATE ${replace ? 'OR REPLACE' : ''} FUNCTION ${ident(schema!)}.${ident(name!)}(${
- args?.join(', ') || ''
- })
- RETURNS ${return_type}
+): SafeSqlFragment {
+ const argsFragment = args && args.length > 0 ? joinSqlFragments(args, ', ') : safeSql``
+ const configParamsFragment =
+ config_params && Object.keys(config_params).length > 0
+ ? joinSqlFragments(
+ Object.entries(config_params).map(([param, value]) =>
+ value === 'FROM CURRENT'
+ ? safeSql`SET ${qualifiedIdent(param)} FROM CURRENT`
+ : safeSql`SET ${qualifiedIdent(param)} TO ${value}`
+ ),
+ '\n'
+ )
+ : safeSql``
+
+ return safeSql`
+ CREATE ${replace ? safeSql`OR REPLACE` : safeSql``} FUNCTION ${ident(schema!)}.${ident(name!)}(${argsFragment})
+ RETURNS ${return_type!}
AS ${literal(definition)}
- LANGUAGE ${language}
- ${behavior}
+ LANGUAGE ${keyword(language!)}
+ ${keyword(behavior!)}
CALLED ON NULL INPUT
- ${security_definer ? 'SECURITY DEFINER' : 'SECURITY INVOKER'}
- ${
- config_params
- ? Object.entries(config_params)
- .map(
- ([param, value]) =>
- `SET ${param} ${value === 'FROM CURRENT' ? 'FROM CURRENT' : 'TO ' + (value === '""' ? "''" : value)}`
- )
- .join('\n')
- : ''
- };
+ ${security_definer ? safeSql`SECURITY DEFINER` : safeSql`SECURITY INVOKER`}
+ ${configParamsFragment};
`
}
@@ -220,7 +275,7 @@ export function create({
schema = 'public',
args = [],
definition,
- return_type = 'void',
+ return_type = safeSql`void`,
language = 'sql',
behavior = 'VOLATILE',
security_definer = false,
@@ -252,53 +307,54 @@ export const pgFunctionUpdateZod = z.object({
export type PGFunctionUpdate = z.infer<typeof pgFunctionUpdateZod>
-export function update(currentFunc: PGFunction, { name, schema, definition }: PGFunctionUpdate) {
- const args = currentFunc.argument_types.split(', ')
+function splitArgumentTypes(argumentTypes: SafeSqlFragment): Array<SafeSqlFragment> {
+ return argumentTypes.split(', ') as Array<SafeSqlFragment>
+}
+
+export function update(
+ currentFunc: PGSavedFunction,
+ { name, schema, definition }: PGFunctionUpdate
+): { sql: SafeSqlFragment; zod: z.ZodType<void> } {
+ const args = splitArgumentTypes(currentFunc.argument_types)
const identityArgs = currentFunc.identity_argument_types
const updateDefinitionSql =
typeof definition === 'string'
? _generateCreateFunctionSql(
{
- ...currentFunc!,
+ ...currentFunc,
definition,
args,
- config_params: currentFunc!.config_params ?? {},
+ config_params: currentFunc.config_params ?? {},
},
{ replace: true }
)
- : ''
+ : safeSql``
const updateNameSql =
- name && name !== currentFunc!.name
- ? `ALTER FUNCTION ${ident(currentFunc!.schema)}.${ident(
- currentFunc!.name
- )}(${identityArgs}) RENAME TO ${ident(name)};`
- : ''
+ name && name !== currentFunc.name
+ ? safeSql`ALTER FUNCTION ${ident(currentFunc.schema)}.${ident(currentFunc.name)}(${identityArgs}) RENAME TO ${ident(name)};`
+ : safeSql``
const updateSchemaSql =
- schema && schema !== currentFunc!.schema
- ? `ALTER FUNCTION ${ident(currentFunc!.schema)}.${ident(
- name || currentFunc!.name
- )}(${identityArgs}) SET SCHEMA ${ident(schema)};`
- : ''
+ schema && schema !== currentFunc.schema
+ ? safeSql`ALTER FUNCTION ${ident(currentFunc.schema)}.${ident(name || currentFunc.name)}(${identityArgs}) SET SCHEMA ${ident(schema)};`
+ : safeSql``
- const sql = /* SQL */ `
+ const sql = safeSql`
DO LANGUAGE plpgsql $$
BEGIN
- IF ${typeof definition === 'string' ? 'TRUE' : 'FALSE'} THEN
+ IF ${typeof definition === 'string' ? safeSql`TRUE` : safeSql`FALSE`} THEN
${updateDefinitionSql}
IF (
SELECT id
FROM (${FUNCTIONS_SQL}) AS f
- WHERE f.schema = ${literal(currentFunc!.schema)}
- AND f.name = ${literal(currentFunc!.name)}
+ WHERE f.schema = ${literal(currentFunc.schema)}
+ AND f.name = ${literal(currentFunc.name)}
AND f.identity_argument_types = ${literal(identityArgs)}
- ) != ${currentFunc.id} THEN
- RAISE EXCEPTION 'Cannot find function "${currentFunc!.schema}"."${
- currentFunc!.name
- }"(${identityArgs})';
+ ) != ${literal(currentFunc.id)} THEN
+ RAISE EXCEPTION ${literal(`Cannot find function "${currentFunc.schema}"."${currentFunc.name}"(${identityArgs})`)};
END IF;
END IF;
@@ -321,10 +377,11 @@ export const pgFunctionDeleteZod = z.object({
export type PGFunctionDelete = z.infer<typeof pgFunctionDeleteZod>
-export function remove(func: PGFunction, { cascade = false }: PGFunctionDelete = {}) {
- const sql = /* SQL */ `DROP FUNCTION ${ident(func.schema)}.${ident(func.name)}
- (${func.identity_argument_types})
- ${cascade ? 'CASCADE' : 'RESTRICT'};`
+export function remove(
+ func: PGSavedFunction,
+ { cascade = false }: PGFunctionDelete = {}
+): { sql: SafeSqlFragment; zod: z.ZodType<void> } {
+ const sql = safeSql`DROP FUNCTION ${ident(func.schema)}.${ident(func.name)}(${func.identity_argument_types}) ${cascade ? safeSql`CASCADE` : safeSql`RESTRICT`};`
return {
sql,
diff --git a/packages/pg-meta/src/pg-meta-policies.ts b/packages/pg-meta/src/pg-meta-policies.ts
index cf82713820e..d628095aac4 100644
--- a/packages/pg-meta/src/pg-meta-policies.ts
+++ b/packages/pg-meta/src/pg-meta-policies.ts
@@ -2,7 +2,14 @@ import { z } from 'zod'
import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
import { filterByList } from './helpers'
-import { ident, literal, safeSql, type SafeSqlFragment } from './pg-format'
+import {
+ ident,
+ joinSqlFragments,
+ keyword,
+ literal,
+ safeSql,
+ type SafeSqlFragment,
+} from './pg-format'
import { POLICIES_SQL } from './sql/policies'
const pgPolicyZod = z.object({
@@ -95,8 +102,8 @@ type PolicyCreateParams = {
name: string
schema?: string
table: string
- definition?: string
- check?: string
+ definition?: SafeSqlFragment
+ check?: SafeSqlFragment
action?: 'PERMISSIVE' | 'RESTRICTIVE'
command?: 'ALL' | 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE'
roles?: string[]
@@ -111,38 +118,47 @@ function create({
action = 'PERMISSIVE',
command = 'ALL',
roles = ['public'],
-}: PolicyCreateParams): { sql: string } {
- const sql = `
+}: PolicyCreateParams): { sql: SafeSqlFragment } {
+ const rolesFragment = joinSqlFragments(roles.map(ident), ', ')
+ const definitionSql = definition ? safeSql`using (${definition})` : safeSql``
+ const checkSql = check ? safeSql`with check (${check})` : safeSql``
+ const sql = safeSql`
create policy ${ident(name)} on ${ident(schema)}.${ident(table)}
- as ${action}
- for ${command}
- to ${roles.map(ident).join(',')}
- ${definition ? `using (${definition})` : ''}
- ${check ? `with check (${check})` : ''};`
+ as ${keyword(action)}
+ for ${keyword(command)}
+ to ${rolesFragment}
+ ${definitionSql}
+ ${checkSql};`
return { sql }
}
type PolicyUpdateParams = {
name?: string
- definition?: string
- check?: string
+ definition?: SafeSqlFragment
+ check?: SafeSqlFragment
roles?: string[]
}
function update(
identifier: Pick<PGPolicy, 'name' | 'schema' | 'table'>,
params: PolicyUpdateParams
-): { sql: string } {
+): { sql: SafeSqlFragment } {
const { name, definition, check, roles } = params
- const alter = `ALTER POLICY ${ident(identifier.name)} ON ${ident(identifier.schema)}.${ident(identifier.table)}`
- const nameSql = name === undefined ? '' : `${alter} RENAME TO ${ident(name)};`
- const definitionSql = definition === undefined ? '' : `${alter} USING (${definition});`
- const checkSql = check === undefined ? '' : `${alter} WITH CHECK (${check});`
- const rolesSql = roles === undefined ? '' : `${alter} TO ${roles.map(ident).join(',')};`
+ const alter = safeSql`ALTER POLICY ${ident(identifier.name)} ON ${ident(identifier.schema)}.${ident(identifier.table)}`
+ const nameSql: SafeSqlFragment =
+ name === undefined ? safeSql`` : safeSql`${alter} RENAME TO ${ident(name)};`
+ const definitionSql: SafeSqlFragment =
+ definition === undefined ? safeSql`` : safeSql`${alter} USING (${definition});`
+ const checkSql: SafeSqlFragment =
+ check === undefined ? safeSql`` : safeSql`${alter} WITH CHECK (${check});`
+ const rolesSql: SafeSqlFragment =
+ roles === undefined
+ ? safeSql``
+ : safeSql`${alter} TO ${joinSqlFragments(roles.map(ident), ', ')};`
// nameSql must be last
- const sql = `BEGIN; ${definitionSql} ${checkSql} ${rolesSql} ${nameSql} COMMIT;`
+ const sql = safeSql`BEGIN; ${definitionSql} ${checkSql} ${rolesSql} ${nameSql} COMMIT;`
return { sql }
}
diff --git a/packages/pg-meta/src/pg-meta-triggers.ts b/packages/pg-meta/src/pg-meta-triggers.ts
index 7bc999be875..551ed3932c8 100644
--- a/packages/pg-meta/src/pg-meta-triggers.ts
+++ b/packages/pg-meta/src/pg-meta-triggers.ts
@@ -2,7 +2,14 @@ import { z } from 'zod'
import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
import { filterByList } from './helpers'
-import { ident, keyword, literal, safeSql, type SafeSqlFragment } from './pg-format'
+import {
+ ident,
+ joinSqlFragments,
+ keyword,
+ literal,
+ safeSql,
+ type SafeSqlFragment,
+} from './pg-format'
import { TRIGGERS_SQL } from './sql/triggers'
type TriggerIdentifier = Pick<PGTrigger, 'id'> | Pick<PGTrigger, 'name' | 'schema' | 'table'>
@@ -103,7 +110,13 @@ export const pgTriggerCreateZod = z.object({
condition: z.string().optional(),
})
-export type PGTriggerCreate = z.infer<typeof pgTriggerCreateZod>
+// Zod validates `condition` as a runtime string; the SafeSqlFragment brand is a
+// separate compile-time trust check. A parsed string is not automatically safe —
+// callers must promote untrusted input via acceptUntrustedSql/rawSql before it can
+// satisfy this type.
+export type PGTriggerCreate = Omit<z.infer<typeof pgTriggerCreateZod>, 'condition'> & {
+ condition?: SafeSqlFragment
+}
export function create({
name,
@@ -117,19 +130,18 @@ export function create({
orientation,
condition,
}: PGTriggerCreate): {
- sql: string
+ sql: SafeSqlFragment
zod: z.ZodType<void>
} {
- const qualifiedTableName = `${ident(schema)}.${ident(table)}`
- const qualifiedFunctionName = `${ident(function_schema)}.${ident(function_name)}`
- const triggerEvents = events.join(' or ')
- const triggerOrientation = orientation ? `for each ${orientation}` : ''
- const triggerCondition = condition ? `when (${condition})` : ''
- const functionArgsStr = function_args.map(literal).join(',')
-
- const sql = `create trigger ${ident(
- name
- )} ${activation} ${triggerEvents} on ${qualifiedTableName} ${triggerOrientation} ${triggerCondition} execute function ${qualifiedFunctionName}(${functionArgsStr});`
+ const qualifiedTableName = safeSql`${ident(schema)}.${ident(table)}`
+ const qualifiedFunctionName = safeSql`${ident(function_schema)}.${ident(function_name)}`
+ const triggerEvents = joinSqlFragments(events.map(keyword), ' or ')
+ const triggerOrientation = orientation ? safeSql`for each ${keyword(orientation)}` : safeSql``
+ const triggerCondition = condition ? safeSql`when (${condition})` : safeSql``
+ const functionArgsFragment =
+ function_args.length > 0 ? joinSqlFragments(function_args.map(literal), ',') : safeSql``
+
+ const sql = safeSql`create trigger ${ident(name)} ${keyword(activation)} ${triggerEvents} on ${qualifiedTableName} ${triggerOrientation} ${triggerCondition} execute function ${qualifiedFunctionName}(${functionArgsFragment});`
return {
sql,
diff --git a/packages/pg-meta/src/query/QueryModifier.ts b/packages/pg-meta/src/query/QueryModifier.ts
index 40a5807024e..42a1047bd12 100644
--- a/packages/pg-meta/src/query/QueryModifier.ts
+++ b/packages/pg-meta/src/query/QueryModifier.ts
@@ -11,7 +11,7 @@ import type { ActionConfig, Filter, QueryPagination, QueryTable, Sort } from './
export interface IQueryModifier {
range: (from: number, to: number) => QueryModifier
- toSql: () => string
+ toSql: () => SafeSqlFragment
}
export class QueryModifier implements IQueryModifier {
diff --git a/packages/pg-meta/test/functions.test.ts b/packages/pg-meta/test/functions.test.ts
index 0d9f7d6c036..530699fe1af 100644
--- a/packages/pg-meta/test/functions.test.ts
+++ b/packages/pg-meta/test/functions.test.ts
@@ -1,11 +1,13 @@
-import { afterAll, beforeAll, expect, test } from 'vitest'
+import { afterAll, expect, test } from 'vitest'
-import pgMeta from '../src/index'
+import pgMeta, { safeSql } from '../src/index'
+import type { PGFunction, PGSavedFunction } from '../src/pg-meta-functions'
import { cleanupRoot, createTestDatabase } from './db/utils'
-beforeAll(async () => {
- // Any global setup if needed
-})
+// Test fixtures originate from `executeQuery` results that match the
+// API/database boundary; brand the raw-SQL fields so they satisfy
+// `update`/`remove` parameter types.
+const asSavedFunction = (fn: PGFunction): PGSavedFunction => fn as unknown as PGSavedFunction
afterAll(async () => {
await cleanupRoot()
@@ -26,7 +28,7 @@ const withTestDatabase = (
}
withTestDatabase('list functions', async ({ executeQuery }) => {
- const { sql, zod } = await pgMeta.functions.list()
+ const { sql, zod } = pgMeta.functions.list()
const res = zod.parse(await executeQuery(sql))
// Test for the 'add' function created in init.sql
@@ -75,7 +77,7 @@ withTestDatabase('list functions', async ({ executeQuery }) => {
})
withTestDatabase('list functions with included schemas', async ({ executeQuery }) => {
- const { sql, zod } = await pgMeta.functions.list({
+ const { sql, zod } = pgMeta.functions.list({
includedSchemas: ['public'],
})
const res = zod.parse(await executeQuery(sql))
@@ -87,7 +89,7 @@ withTestDatabase('list functions with included schemas', async ({ executeQuery }
})
withTestDatabase('list functions with excluded schemas', async ({ executeQuery }) => {
- const { sql, zod } = await pgMeta.functions.list({
+ const { sql, zod } = pgMeta.functions.list({
excludedSchemas: ['public'],
})
const res = zod.parse(await executeQuery(sql))
@@ -100,7 +102,7 @@ withTestDatabase('list functions with excluded schemas', async ({ executeQuery }
withTestDatabase(
'list functions with excluded schemas and include System Schemas',
async ({ executeQuery }) => {
- const { sql, zod } = await pgMeta.functions.list({
+ const { sql, zod } = pgMeta.functions.list({
excludedSchemas: ['public'],
includeSystemSchemas: true,
})
@@ -115,21 +117,21 @@ withTestDatabase(
withTestDatabase('retrieve, create, update, delete', async ({ executeQuery }) => {
// Create function
- const { sql: createSql } = await pgMeta.functions.create({
+ const { sql: createSql } = pgMeta.functions.create({
name: 'test_func',
schema: 'public',
- args: ['a int2', 'b int2'],
+ args: [safeSql`a int2`, safeSql`b int2`],
definition: 'select a + b',
- return_type: 'integer',
+ return_type: safeSql`integer`,
language: 'sql',
behavior: 'STABLE',
security_definer: true,
- config_params: { search_path: 'hooks, auth', role: 'postgres' },
+ config_params: { search_path: safeSql`hooks, auth`, role: safeSql`postgres` },
})
await executeQuery(createSql)
// // Retrieve function
- const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.functions.retrieve({
+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.functions.retrieve({
name: 'test_func',
schema: 'public',
args: ['a int2', 'b int2'],
@@ -187,16 +189,16 @@ withTestDatabase('retrieve, create, update, delete', async ({ executeQuery }) =>
`
)
// create test_schema to move the function into:
- const { sql: createSchemaSql } = await pgMeta.schemas.create({ name: 'test_schema' })
+ const { sql: createSchemaSql } = pgMeta.schemas.create({ name: 'test_schema' })
await executeQuery(createSchemaSql)
- const { sql: updateSql } = await pgMeta.functions.update(res!, {
+ const { sql: updateSql } = pgMeta.functions.update(asSavedFunction(res!), {
name: 'test_func_renamed',
schema: 'test_schema',
definition: 'select b - a',
})
await executeQuery(updateSql)
- const { sql: retrieveRenamedSql } = await pgMeta.functions.retrieve({ id: functionId })
+ const { sql: retrieveRenamedSql } = pgMeta.functions.retrieve({ id: functionId })
const retrieveRenamed = await executeQuery(retrieveRenamedSql)
const resUpdated = retrieveZod.parse(retrieveRenamed[0])
expect({ data: resUpdated, error: null }).toMatchInlineSnapshot(
@@ -250,17 +252,17 @@ withTestDatabase('retrieve, create, update, delete', async ({ executeQuery }) =>
)
// Remove function
- const { sql: removeSql } = await pgMeta.functions.remove(resUpdated!)
+ const { sql: removeSql } = pgMeta.functions.remove(asSavedFunction(resUpdated!))
await executeQuery(removeSql)
// Verify function is removed
- const { sql: verifyRemoveSql } = await pgMeta.functions.retrieve({ id: functionId })
+ const { sql: verifyRemoveSql } = pgMeta.functions.retrieve({ id: functionId })
const result = await executeQuery(verifyRemoveSql)
expect(result).toHaveLength(0)
})
withTestDatabase('retrieve set-returning function', async ({ executeQuery }) => {
// Retrieve function
- const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.functions.retrieve({
+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.functions.retrieve({
schema: 'public',
name: 'function_returning_set_of_rows',
args: [],
@@ -309,22 +311,22 @@ withTestDatabase('create function with various config_params values', async ({ e
// Set initial application_name for consistent testing
await executeQuery("SET application_name = 'current-app-name'")
- const { sql: createSql1 } = await pgMeta.functions.create({
+ const { sql: createSql1 } = pgMeta.functions.create({
name: 'test_func_config_1',
schema: 'public',
definition: 'select 1',
- return_type: 'integer',
+ return_type: safeSql`integer`,
language: 'sql',
config_params: {
- search_path: '""', // Should become ''
+ search_path: safeSql`''`, // Quoted empty string
application_name: 'FROM CURRENT', // Special syntax: SET param FROM CURRENT
- work_mem: "'8MB'", // Regular syntax: SET param TO value
+ work_mem: safeSql`'8MB'`, // Regular syntax: SET param TO value
},
})
await executeQuery(createSql1)
// Verify the function was created correctly
- const { sql: retrieveSql1, zod: retrieveZod } = await pgMeta.functions.retrieve({
+ const { sql: retrieveSql1, zod: retrieveZod } = pgMeta.functions.retrieve({
name: 'test_func_config_1',
schema: 'public',
args: [],
@@ -339,6 +341,38 @@ withTestDatabase('create function with various config_params values', async ({ e
})
// Clean up
- const { sql: removeSql1 } = await pgMeta.functions.remove(result1!)
+ const { sql: removeSql1 } = pgMeta.functions.remove(asSavedFunction(result1!))
await executeQuery(removeSql1)
})
+
+withTestDatabase(
+ 'create function with namespaced custom GUC config_params',
+ async ({ executeQuery }) => {
+ const { sql: createSql } = pgMeta.functions.create({
+ name: 'test_func_namespaced_guc',
+ schema: 'public',
+ definition: 'select 1',
+ return_type: safeSql`integer`,
+ language: 'sql',
+ config_params: {
+ 'app.jwt_secret': safeSql`'top-secret'`,
+ },
+ })
+ await executeQuery(createSql)
+
+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.functions.retrieve({
+ name: 'test_func_namespaced_guc',
+ schema: 'public',
+ args: [],
+ })
+ const result = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+
+ expect(result).toBeDefined()
+ expect(result!.config_params).toEqual({
+ 'app.jwt_secret': 'top-secret',
+ })
+
+ const { sql: removeSql } = pgMeta.functions.remove(asSavedFunction(result!))
+ await executeQuery(removeSql)
+ }
+)
diff --git a/packages/pg-meta/test/policies.test.ts b/packages/pg-meta/test/policies.test.ts
index 1d31e70f314..624c8480180 100644
--- a/packages/pg-meta/test/policies.test.ts
+++ b/packages/pg-meta/test/policies.test.ts
@@ -1,6 +1,6 @@
import { afterAll, expect, test } from 'vitest'
-import pgMeta from '../src/index'
+import pgMeta, { safeSql } from '../src/index'
import { cleanupRoot, createTestDatabase } from './db/utils'
afterAll(async () => {
@@ -97,8 +97,8 @@ withTestDatabase('retrieve, create, update, delete policies', async ({ executeQu
// Update policy
const { sql: updateSql } = pgMeta.policies.update(createdPolicy!, {
name: 'updated_policy',
- definition: "current_setting('my.username') IN (name)",
- check: "current_setting('my.username') IN (name)",
+ definition: safeSql`current_setting('my.username') IN (name)`,
+ check: safeSql`current_setting('my.username') IN (name)`,
roles: ['postgres'],
})
await executeQuery(updateSql)
diff --git a/packages/pg-meta/test/triggers.test.ts b/packages/pg-meta/test/triggers.test.ts
index 04ddd382c16..e6362a6bbc3 100644
--- a/packages/pg-meta/test/triggers.test.ts
+++ b/packages/pg-meta/test/triggers.test.ts
@@ -1,6 +1,6 @@
import { afterAll, beforeAll, expect, test } from 'vitest'
-import pgMeta from '../src/index'
+import pgMeta, { safeSql } from '../src/index'
import { cleanupRoot, createTestDatabase } from './db/utils'
beforeAll(async () => {
@@ -37,7 +37,7 @@ withTestDatabase('retrieve, create, update, delete', async ({ executeQuery }) =>
activation: 'AFTER',
events: ['UPDATE'],
orientation: 'ROW',
- condition: '(old.* IS DISTINCT FROM new.*)',
+ condition: safeSql`(old.* IS DISTINCT FROM new.*)`,
})
await executeQuery(createSql)