Skip to content

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

fix: only use MAINTAIN for table privileges if PG17+ (#30998)

Bobbie Soedirgof5c0a4c8997f
diff --git a/apps/studio/components/interfaces/Database/Privileges/Privileges.utils.ts b/apps/studio/components/interfaces/Database/Privileges/Privileges.utils.ts
index 42d9d4e6250..90b08108777 100644
--- a/apps/studio/components/interfaces/Database/Privileges/Privileges.utils.ts
+++ b/apps/studio/components/interfaces/Database/Privileges/Privileges.utils.ts
@@ -15,7 +15,7 @@ import {
TablePrivilegesGrant,
grantTablePrivileges,
} from 'data/privileges/table-privileges-grant-mutation'
-import type { TablePrivilege } from 'data/privileges/table-privileges-query'
+import type { PgTablePrivileges } from 'data/privileges/table-privileges-query'
import {
TablePrivilegesRevoke,
revokeTablePrivileges,
@@ -35,7 +35,7 @@ export interface PrivilegeOperation {
privilege_type: string
}
-export function getDefaultTableCheckedStates(tablePrivilege: TablePrivilege) {
+export function getDefaultTableCheckedStates(tablePrivilege: PgTablePrivileges) {
return Object.fromEntries(
ALL_PRIVILEGE_TYPES.map((privilege) => [
privilege,
@@ -286,16 +286,16 @@ export function useApplyPrivilegeOperations(callback?: () => void) {
const grantTableOperations = tableOperations
.filter((op) => op.type === 'grant')
.map((op) => ({
- relation_id: Number(op.id),
+ relationId: Number(op.id),
grantee: op.grantee,
- privilege_type: op.privilege_type as TablePrivilegesGrant['privilege_type'],
+ privilegeType: op.privilege_type as TablePrivilegesGrant['privilegeType'],
}))
const revokeTableOperations = tableOperations
.filter((op) => op.type === 'revoke')
.map((op) => ({
- relation_id: Number(op.id),
+ relationId: Number(op.id),
grantee: op.grantee,
- privilege_type: op.privilege_type as TablePrivilegesRevoke['privilege_type'],
+ privilegeType: op.privilege_type as TablePrivilegesRevoke['privilegeType'],
}))
const grantColumnOperations = columnOperations
diff --git a/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueSettings.tsx b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueSettings.tsx
index b4bf5834669..0ec77ac6113 100644
--- a/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueSettings.tsx
+++ b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueSettings.tsx
@@ -147,8 +147,8 @@ export const QueueSettings = ({}: QueueSettingsProps) => {
connectionString: project.connectionString,
revokes: revoke.map((x) => ({
grantee: x.role,
- privilege_type: x.action.toUpperCase(),
- relation_id: queueTable.id,
+ privilegeType: x.action.toUpperCase(),
+ relationId: queueTable.id,
})) as TablePrivilegesRevoke[],
}),
]
@@ -162,13 +162,13 @@ export const QueueSettings = ({}: QueueSettingsProps) => {
revokes: [
...rolesNoLongerHavingPerms.map((x) => ({
grantee: x,
- privilege_type: 'INSERT' as 'INSERT',
- relation_id: archiveTable.id,
+ privilegeType: 'INSERT' as const,
+ relationId: archiveTable.id,
})),
...rolesNoLongerHavingPerms.map((x) => ({
grantee: x,
- privilege_type: 'SELECT' as 'SELECT',
- relation_id: archiveTable.id,
+ privilegeType: 'SELECT' as const,
+ relationId: archiveTable.id,
})),
],
}),
@@ -181,8 +181,8 @@ export const QueueSettings = ({}: QueueSettingsProps) => {
connectionString: project.connectionString,
grants: grant.map((x) => ({
grantee: x.role,
- privilege_type: x.action.toUpperCase(),
- relation_id: queueTable.id,
+ privilegeType: x.action.toUpperCase(),
+ relationId: queueTable.id,
})) as TablePrivilegesGrant[],
}),
// Just grant select + insert on archive table as long as we're granting any perms to the queue table for the role
@@ -192,13 +192,13 @@ export const QueueSettings = ({}: QueueSettingsProps) => {
grants: [
...rolesBeingGrantedPerms.map((x) => ({
grantee: x,
- privilege_type: 'INSERT' as 'INSERT',
- relation_id: archiveTable.id,
+ privilegeType: 'INSERT' as const,
+ relationId: archiveTable.id,
})),
...rolesBeingGrantedPerms.map((x) => ({
grantee: x,
- privilege_type: 'SELECT' as 'SELECT',
- relation_id: archiveTable.id,
+ privilegeType: 'SELECT' as const,
+ relationId: archiveTable.id,
})),
],
}),
diff --git a/apps/studio/data/privileges/table-privileges-grant-mutation.ts b/apps/studio/data/privileges/table-privileges-grant-mutation.ts
index bd44e9b5ed7..9d086536fa1 100644
--- a/apps/studio/data/privileges/table-privileges-grant-mutation.ts
+++ b/apps/studio/data/privileges/table-privileges-grant-mutation.ts
@@ -1,12 +1,17 @@
+import pgMeta from '@supabase/pg-meta'
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
-import type { components } from 'data/api'
-import { handleError, post } from 'data/fetchers'
+import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError } from 'types'
+import { invalidateTablePrivilegesQuery } from './table-privileges-query'
import { privilegeKeys } from './keys'
-export type TablePrivilegesGrant = components['schemas']['GrantTablePrivilegesBody']
+export type TablePrivilegesGrant = Parameters<
+ typeof pgMeta.tablePrivileges.grant
+>[0] extends (infer T)[]
+ ? T
+ : never
export type TablePrivilegesGrantVariables = {
projectRef: string
@@ -19,21 +24,14 @@ export async function grantTablePrivileges({
connectionString,
grants,
}: TablePrivilegesGrantVariables) {
- const headers = new Headers()
- if (connectionString) headers.set('x-connection-encrypted', connectionString)
-
- const { data, error } = await post('/platform/pg-meta/{ref}/table-privileges', {
- params: {
- path: { ref: projectRef },
- // this is needed to satisfy the typescript, but it doesn't pass the actual header
- header: { 'x-connection-encrypted': connectionString! },
- },
- body: grants,
- headers,
+ const sql = pgMeta.tablePrivileges.grant(grants).sql
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql,
+ queryKey: ['table-privileges', 'grant'],
})
-
- if (error) handleError(error)
- return data
+ return result
}
type TablePrivilegesGrantData = Awaited<ReturnType<typeof grantTablePrivileges>>
@@ -55,7 +53,7 @@ export const useTablePrivilegesGrantMutation = ({
const { projectRef } = variables
await Promise.all([
- queryClient.invalidateQueries(privilegeKeys.tablePrivilegesList(projectRef)),
+ invalidateTablePrivilegesQuery(queryClient, projectRef),
queryClient.invalidateQueries(privilegeKeys.columnPrivilegesList(projectRef)),
])
diff --git a/apps/studio/data/privileges/table-privileges-query.ts b/apps/studio/data/privileges/table-privileges-query.ts
index 6d3f961a721..4b86f2a4420 100644
--- a/apps/studio/data/privileges/table-privileges-query.ts
+++ b/apps/studio/data/privileges/table-privileges-query.ts
@@ -1,8 +1,8 @@
-import { UseQueryOptions, useQuery } from '@tanstack/react-query'
+import pgMeta from '@supabase/pg-meta'
+import { QueryClient, UseQueryOptions, useQuery } from '@tanstack/react-query'
+import { z } from 'zod'
-import type { components } from 'data/api'
-import { get, handleError } from 'data/fetchers'
-import type { ResponseError } from 'types'
+import { executeSql, ExecuteSqlError } from 'data/sql/execute-sql-query'
import { privilegeKeys } from './keys'
export type TablePrivilegesVariables = {
@@ -10,34 +10,30 @@ export type TablePrivilegesVariables = {
connectionString?: string
}
-export type TablePrivilege = components['schemas']['PostgresTablePrivileges']
+export type PgTablePrivileges = z.infer<typeof pgMeta.tablePrivileges.zod>
-export async function getTablePrivileges(
+const pgMetaTablePrivilegesList = pgMeta.tablePrivileges.list()
+
+export type TablePrivilegesData = z.infer<typeof pgMetaTablePrivilegesList.zod>
+export type TablePrivilegesError = ExecuteSqlError
+
+async function getTablePrivileges(
{ projectRef, connectionString }: TablePrivilegesVariables,
signal?: AbortSignal
) {
- if (!projectRef) throw new Error('projectRef is required')
-
- const headers = new Headers()
- if (connectionString) headers.set('x-connection-encrypted', connectionString)
-
- const { data, error } = await get('/platform/pg-meta/{ref}/table-privileges', {
- params: {
- path: { ref: projectRef },
- // this is needed to satisfy the typescript, but it doesn't pass the actual header
- header: { 'x-connection-encrypted': connectionString! },
+ const { result } = await executeSql(
+ {
+ projectRef,
+ connectionString,
+ sql: pgMetaTablePrivilegesList.sql,
+ queryKey: ['table-privileges'],
},
- signal,
- headers,
- })
+ signal
+ )
- if (error) throw handleError(error)
- return data
+ return result as TablePrivilegesData
}
-export type TablePrivilegesData = Awaited<ReturnType<typeof getTablePrivileges>>
-export type TablePrivilegesError = ResponseError
-
export const useTablePrivilegesQuery = <TData = TablePrivilegesData>(
{ projectRef, connectionString }: TablePrivilegesVariables,
{
@@ -53,3 +49,10 @@ export const useTablePrivilegesQuery = <TData = TablePrivilegesData>(
...options,
}
)
+
+export function invalidateTablePrivilegesQuery(
+ client: QueryClient,
+ projectRef: string | undefined
+) {
+ return client.invalidateQueries(privilegeKeys.tablePrivilegesList(projectRef))
+}
diff --git a/apps/studio/data/privileges/table-privileges-revoke-mutation.ts b/apps/studio/data/privileges/table-privileges-revoke-mutation.ts
index 888d2780c03..cfb2bb8e288 100644
--- a/apps/studio/data/privileges/table-privileges-revoke-mutation.ts
+++ b/apps/studio/data/privileges/table-privileges-revoke-mutation.ts
@@ -1,12 +1,17 @@
+import pgMeta from '@supabase/pg-meta'
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
-import type { components } from 'data/api'
-import { del, handleError } from 'data/fetchers'
+import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError } from 'types'
+import { invalidateTablePrivilegesQuery } from './table-privileges-query'
import { privilegeKeys } from './keys'
-export type TablePrivilegesRevoke = components['schemas']['RevokeTablePrivilegesBody']
+export type TablePrivilegesRevoke = Parameters<
+ typeof pgMeta.tablePrivileges.revoke
+>[0] extends (infer T)[]
+ ? T
+ : never
export type TablePrivilegesRevokeVariables = {
projectRef: string
@@ -19,21 +24,14 @@ export async function revokeTablePrivileges({
connectionString,
revokes,
}: TablePrivilegesRevokeVariables) {
- const headers = new Headers()
- if (connectionString) headers.set('x-connection-encrypted', connectionString)
-
- const { data, error } = await del('/platform/pg-meta/{ref}/table-privileges', {
- params: {
- path: { ref: projectRef },
- // this is needed to satisfy the typescript, but it doesn't pass the actual header
- header: { 'x-connection-encrypted': connectionString! },
- },
- body: revokes,
- headers,
+ const sql = pgMeta.tablePrivileges.revoke(revokes).sql
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql,
+ queryKey: ['table-privileges', 'revoke'],
})
-
- if (error) handleError(error)
- return data
+ return result
}
type TablePrivilegesRevokeData = Awaited<ReturnType<typeof revokeTablePrivileges>>
@@ -55,7 +53,7 @@ export const useTablePrivilegesRevokeMutation = ({
const { projectRef } = variables
await Promise.all([
- queryClient.invalidateQueries(privilegeKeys.tablePrivilegesList(projectRef)),
+ invalidateTablePrivilegesQuery(queryClient, projectRef),
queryClient.invalidateQueries(privilegeKeys.columnPrivilegesList(projectRef)),
])
diff --git a/apps/studio/pages/api/pg-meta/[ref]/table-privileges.ts b/apps/studio/pages/api/pg-meta/[ref]/table-privileges.ts
deleted file mode 100644
index 13f805dbbaa..00000000000
--- a/apps/studio/pages/api/pg-meta/[ref]/table-privileges.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { NextApiRequest, NextApiResponse } from 'next'
-
-import { constructHeaders } from 'lib/api/apiHelpers'
-import apiWrapper from 'lib/api/apiWrapper'
-import { delete_, get, post } from 'lib/common/fetch'
-import { PG_META_URL } from 'lib/constants'
-import { getPgMetaRedirectUrl } from './tables'
-
-export default (req: NextApiRequest, res: NextApiResponse) =>
- apiWrapper(req, res, handler, { withAuth: true })
-
-async function handler(req: NextApiRequest, res: NextApiResponse) {
- const { method } = req
- switch (method) {
- case 'GET':
- return handleGetAll(req, res)
- case 'POST':
- return handlePost(req, res)
- case 'DELETE':
- return handleDelete(req, res)
- default:
- res.setHeader('Allow', ['GET'])
- res.status(405).json({ error: { message: `Method ${method} Not Allowed` } })
- }
-}
-
-const handleGetAll = async (req: NextApiRequest, res: NextApiResponse) => {
- const headers = constructHeaders(req.headers)
- let response = await get(getPgMetaRedirectUrl(req, 'table-privileges'), {
- headers,
- })
- if (response.error) {
- return res.status(400).json({ error: response.error })
- }
- return res.status(200).json(response)
-}
-
-const handlePost = async (req: NextApiRequest, res: NextApiResponse) => {
- const headers = constructHeaders(req.headers)
- const payload = req.body
- const response = await post(`${PG_META_URL}/table-privileges`, payload, {
- headers,
- })
-
- if (response.error) {
- console.error('Role POST:', response.error)
- return res.status(400).json({ error: response.error })
- }
-
- return res.status(200).json(response)
-}
-
-const handleDelete = async (req: NextApiRequest, res: NextApiResponse) => {
- const headers = constructHeaders(req.headers)
- const payload = req.body
- const response = await delete_(`${PG_META_URL}/table-privileges`, payload, { headers })
-
- if (response.error) {
- console.error('Role DELETE:', response.error)
- return res.status(400).json({ error: response.error })
- }
-
- return res.status(200).json(response)
-}
diff --git a/packages/pg-meta/src/index.ts b/packages/pg-meta/src/index.ts
index 60761df8f85..ae31db484b9 100644
--- a/packages/pg-meta/src/index.ts
+++ b/packages/pg-meta/src/index.ts
@@ -1,9 +1,11 @@
import roles from './pg-meta-roles'
import schemas from './pg-meta-schemas'
import * as functions from './pg-meta-functions'
+import tablePrivileges from './pg-meta-table-privileges'
export default {
roles,
schemas,
functions,
+ tablePrivileges,
}
diff --git a/packages/pg-meta/src/pg-meta-table-privileges.ts b/packages/pg-meta/src/pg-meta-table-privileges.ts
new file mode 100644
index 00000000000..8b08178618d
--- /dev/null
+++ b/packages/pg-meta/src/pg-meta-table-privileges.ts
@@ -0,0 +1,189 @@
+import { ident, literal } from './pg-format'
+import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
+import { TABLE_PRIVILEGES_SQL } from './sql/table-privileges'
+import { z } from 'zod'
+import { filterByList } from './helpers'
+
+const pgTablePrivilegesZod = z.object({
+ relation_id: z.number(),
+ schema: z.string(),
+ name: z.string(),
+ kind: z.union([
+ z.literal('table'),
+ z.literal('view'),
+ z.literal('materialized_view'),
+ z.literal('foreign_table'),
+ z.literal('partitioned_table'),
+ ]),
+ privileges: z.array(
+ z.object({
+ grantor: z.string(),
+ grantee: z.string(),
+ privilege_type: z.union([
+ z.literal('SELECT'),
+ z.literal('INSERT'),
+ z.literal('UPDATE'),
+ z.literal('DELETE'),
+ z.literal('TRUNCATE'),
+ z.literal('REFERENCES'),
+ z.literal('TRIGGER'),
+ z.literal('MAINTAIN'),
+ ]),
+ is_grantable: z.boolean(),
+ })
+ ),
+})
+const pgTablePrivilegesArrayZod = z.array(pgTablePrivilegesZod)
+const pgTablePrivilegesOptionalZod = z.optional(pgTablePrivilegesZod)
+
+function list({
+ includeSystemSchemas = false,
+ includedSchemas,
+ excludedSchemas,
+ limit,
+ offset,
+}: {
+ includeSystemSchemas?: boolean
+ includedSchemas?: string[]
+ excludedSchemas?: string[]
+ limit?: number
+ offset?: number
+} = {}): {
+ sql: string
+ zod: typeof pgTablePrivilegesArrayZod
+} {
+ let sql = `
+with table_privileges as (${TABLE_PRIVILEGES_SQL})
+select *
+from table_privileges
+`
+ const filter = filterByList(
+ includedSchemas,
+ excludedSchemas,
+ !includeSystemSchemas ? DEFAULT_SYSTEM_SCHEMAS : undefined
+ )
+ if (filter) {
+ sql += ` where schema ${filter}`
+ }
+ if (limit) {
+ sql += ` limit ${limit}`
+ }
+ if (offset) {
+ sql += ` offset ${offset}`
+ }
+ return {
+ sql,
+ zod: pgTablePrivilegesArrayZod,
+ }
+}
+
+function retrieve({ id }: { id: number }): { sql: string; zod: typeof pgTablePrivilegesOptionalZod }
+function retrieve({ name, schema }: { name: string; schema?: string }): {
+ sql: string
+ zod: typeof pgTablePrivilegesOptionalZod
+}
+function retrieve({
+ id,
+ name,
+ schema = 'public',
+}: {
+ id?: number
+ name?: string
+ schema?: string
+}): {
+ sql: string
+ zod: typeof pgTablePrivilegesOptionalZod
+} {
+ if (id) {
+ const sql = /* SQL */ `
+with table_privileges as (${TABLE_PRIVILEGES_SQL})
+select *
+from table_privileges
+where table_privileges.relation_id = ${literal(id)};`
+ return {
+ sql,
+ zod: pgTablePrivilegesOptionalZod,
+ }
+ } else {
+ const sql = /* SQL */ `
+with table_privileges as (${TABLE_PRIVILEGES_SQL})
+select *
+from table_privileges
+where table_privileges.schema = ${literal(schema)}
+ and table_privileges.name = ${literal(name)}
+`
+ return {
+ sql,
+ zod: pgTablePrivilegesOptionalZod,
+ }
+ }
+}
+
+type TablePrivilegesGrant = {
+ relationId: number
+ grantee: string
+ privilegeType:
+ | 'ALL'
+ | 'SELECT'
+ | 'INSERT'
+ | 'UPDATE'
+ | 'DELETE'
+ | 'TRUNCATE'
+ | 'REFERENCES'
+ | 'TRIGGER'
+ | 'MAINTAIN'
+ isGrantable?: boolean
+}
+function grant(grants: TablePrivilegesGrant[]): { sql: string } {
+ const sql = `
+do $$
+begin
+${grants
+ .map(
+ ({ privilegeType, relationId, grantee, isGrantable }) =>
+ `execute format('grant ${privilegeType} on table %s to ${
+ grantee.toLowerCase() === 'public' ? 'public' : ident(grantee)
+ } ${isGrantable ? 'with grant option' : ''}', ${relationId}::regclass);`
+ )
+ .join('\n')}
+end $$;
+`
+ return { sql }
+}
+
+type TablePrivilegesRevoke = {
+ relationId: number
+ grantee: string
+ privilegeType:
+ | 'ALL'
+ | 'SELECT'
+ | 'INSERT'
+ | 'UPDATE'
+ | 'DELETE'
+ | 'TRUNCATE'
+ | 'REFERENCES'
+ | 'TRIGGER'
+ | 'MAINTAIN'
+}
+function revoke(revokes: TablePrivilegesRevoke[]): { sql: string } {
+ const sql = `
+do $$
+begin
+${revokes
+ .map(
+ ({ privilegeType, relationId, grantee }) =>
+ `execute format('revoke ${privilegeType} on table %s from ${grantee.toLowerCase() === 'public' ? 'public' : ident(grantee)}', ${relationId}::regclass);`
+ )
+ .join('\n')}
+end $$;
+`
+ return { sql }
+}
+
+export default {
+ list,
+ retrieve,
+ grant,
+ revoke,
+ zod: pgTablePrivilegesZod,
+}
diff --git a/packages/pg-meta/src/sql/table-privileges.ts b/packages/pg-meta/src/sql/table-privileges.ts
new file mode 100644
index 00000000000..ad54a2103c6
--- /dev/null
+++ b/packages/pg-meta/src/sql/table-privileges.ts
@@ -0,0 +1,78 @@
+export const TABLE_PRIVILEGES_SQL = /* SQL */ `
+-- Despite the name \`table_privileges\`, this includes other kinds of relations:
+-- views, matviews, etc. "Relation privileges" just doesn't roll off the tongue.
+--
+-- For each relation, get its relacl in a jsonb format,
+-- e.g.
+--
+-- '{postgres=arwdDxt/postgres}'
+--
+-- becomes
+--
+-- [
+-- {
+-- "grantee": "postgres",
+-- "grantor": "postgres",
+-- "is_grantable": false,
+-- "privilege_type": "INSERT"
+-- },
+-- ...
+-- ]
+select
+ c.oid as relation_id,
+ nc.nspname as schema,
+ c.relname as name,
+ case
+ when c.relkind = 'r' then 'table'
+ when c.relkind = 'v' then 'view'
+ when c.relkind = 'm' then 'materialized_view'
+ when c.relkind = 'f' then 'foreign_table'
+ when c.relkind = 'p' then 'partitioned_table'
+ end as kind,
+ coalesce(
+ jsonb_agg(
+ jsonb_build_object(
+ 'grantor', grantor.rolname,
+ 'grantee', grantee.rolname,
+ 'privilege_type', _priv.privilege_type,
+ 'is_grantable', _priv.is_grantable
+ )
+ ) filter (where _priv is not null),
+ '[]'
+ ) as privileges
+from pg_class c
+join pg_namespace as nc
+ on nc.oid = c.relnamespace
+left join lateral (
+ select grantor, grantee, privilege_type, is_grantable
+ from aclexplode(coalesce(c.relacl, acldefault('r', c.relowner)))
+) as _priv on true
+left join pg_roles as grantor
+ on grantor.oid = _priv.grantor
+left join (
+ select
+ pg_roles.oid,
+ pg_roles.rolname
+ from pg_roles
+ union all
+ select
+ (0)::oid as oid, 'PUBLIC'
+) as grantee (oid, rolname)
+ on grantee.oid = _priv.grantee
+where c.relkind in ('r', 'v', 'm', 'f', 'p')
+ and not pg_is_other_temp_schema(c.relnamespace)
+ and (
+ pg_has_role(c.relowner, 'USAGE')
+ or has_table_privilege(
+ c.oid,
+ 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'
+ || case when current_setting('server_version_num')::int4 >= 170000 then ', MAINTAIN' else '' end
+ )
+ or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')
+ )
+group by
+ c.oid,
+ nc.nspname,
+ c.relname,
+ c.relkind
+`