Skip to content

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

chore(pg-meta): migrate policies (#33680)

Andrew Valleteau44e84ceab325
diff --git a/packages/pg-meta/src/index.ts b/packages/pg-meta/src/index.ts
index 589022d6de3..e146c002e07 100644
--- a/packages/pg-meta/src/index.ts
+++ b/packages/pg-meta/src/index.ts
@@ -2,6 +2,7 @@ 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'
+import policies from './pg-meta-policies'
import triggers from './pg-meta-triggers'
import types from './pg-meta-types'
import version from './pg-meta-version'
@@ -13,6 +14,7 @@ export default {
schemas,
functions,
tablePrivileges,
+ policies,
triggers,
types,
version,
diff --git a/packages/pg-meta/src/pg-meta-policies.ts b/packages/pg-meta/src/pg-meta-policies.ts
new file mode 100644
index 00000000000..d154c1c17cf
--- /dev/null
+++ b/packages/pg-meta/src/pg-meta-policies.ts
@@ -0,0 +1,181 @@
+import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
+import { filterByList } from './helpers'
+import { ident, literal } from './pg-format'
+import { POLICIES_SQL } from './sql/policies'
+import { z } from 'zod'
+
+const pgPolicyZod = z.object({
+ id: z.number(),
+ schema: z.string(),
+ table: z.string(),
+ table_id: z.number(),
+ name: z.string(),
+ action: z.union([z.literal('PERMISSIVE'), z.literal('RESTRICTIVE')]),
+ roles: z.array(z.string()),
+ command: z.union([
+ z.literal('SELECT'),
+ z.literal('INSERT'),
+ z.literal('UPDATE'),
+ z.literal('DELETE'),
+ z.literal('ALL'),
+ ]),
+ definition: z.union([z.string(), z.null()]),
+ check: z.union([z.string(), z.null()]),
+})
+const pgPolicyArrayZod = z.array(pgPolicyZod)
+const pgPolicyOptionalZod = z.optional(pgPolicyZod)
+
+export type PGPolicy = z.infer<typeof pgPolicyZod>
+
+type PolicyIdentifier = Pick<PGPolicy, 'id'> | Pick<PGPolicy, 'name' | 'schema' | 'table'>
+
+function getIdentifierWhereClause(identifier: PolicyIdentifier): string {
+ if ('id' in identifier && identifier.id) {
+ return `id = ${literal(identifier.id)}`
+ } else if ('name' in identifier && identifier.name && identifier.schema && identifier.table) {
+ return `name = ${literal(identifier.name)} AND schema = ${literal(identifier.schema)} AND table = ${literal(identifier.table)}`
+ }
+ throw new Error('Must provide either id or name, schema and table')
+}
+
+function list({
+ includeSystemSchemas = false,
+ includedSchemas,
+ excludedSchemas,
+ limit,
+ offset,
+}: {
+ includeSystemSchemas?: boolean
+ includedSchemas?: string[]
+ excludedSchemas?: string[]
+ limit?: number
+ offset?: number
+} = {}): {
+ sql: string
+ zod: typeof pgPolicyArrayZod
+} {
+ let sql = `
+ with policies as (${POLICIES_SQL})
+ select *
+ from policies
+ `
+ 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: pgPolicyArrayZod,
+ }
+}
+
+function retrieve(identifier: PolicyIdentifier): {
+ sql: string
+ zod: typeof pgPolicyOptionalZod
+} {
+ const sql = `with policies as (${POLICIES_SQL}) select * from policies where ${getIdentifierWhereClause(identifier)};`
+ return {
+ sql,
+ zod: pgPolicyOptionalZod,
+ }
+}
+
+type PolicyCreateParams = {
+ name: string
+ schema?: string
+ table: string
+ definition?: string
+ check?: string
+ action?: 'PERMISSIVE' | 'RESTRICTIVE'
+ command?: 'ALL' | 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE'
+ roles?: string[]
+}
+
+function create({
+ name,
+ schema = 'public',
+ table,
+ definition,
+ check,
+ action = 'PERMISSIVE',
+ command = 'ALL',
+ roles = ['public'],
+}: PolicyCreateParams): { sql: string } {
+ const sql = `
+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})` : ''};`
+ return { sql }
+}
+
+type PolicyUpdateParams = {
+ name?: string
+ definition?: string
+ check?: string
+ roles?: string[]
+}
+
+function update(identifier: PolicyIdentifier, params: PolicyUpdateParams): { sql: string } {
+ const { name, definition, check, roles } = params
+ const indentifyClause = getIdentifierWhereClause(identifier)
+ const sql = `
+do $$
+declare
+ old record;
+begin
+ with policies as (${POLICIES_SQL})
+ select * into old from policies where ${indentifyClause};
+ if old is null then
+ raise exception 'Cannot find policy with id %', ${literal(indentifyClause)};
+ end if;
+
+ ${definition ? `execute(format('alter policy %I on %I.%I using (%s);', old.name, old.schema, old.table, ${literal(definition)}));` : ''}
+ ${check ? `execute(format('alter policy %I on %I.%I with check (%s);', old.name, old.schema, old.table, ${literal(check)}));` : ''}
+ ${roles ? `execute(format('alter policy %I on %I.%I to %s;', old.name, old.schema, old.table, ${literal(roles.map(ident).join(','))}));` : ''}
+ ${name ? `execute(format('alter policy %I on %I.%I rename to %I;', old.name, old.schema, old.table, ${literal(name)}));` : ''}
+end
+$$;`
+ return { sql }
+}
+
+function remove(identifier: PolicyIdentifier): { sql: string } {
+ const indentifyClause = getIdentifierWhereClause(identifier)
+
+ const sql = `
+do $$
+declare
+ old record;
+begin
+ with policies as (${POLICIES_SQL})
+ select * into old from policies where ${indentifyClause};
+ if old is null then
+ raise exception 'Cannot find policy with id %', ${literal(indentifyClause)};
+ end if;
+
+ execute(format('drop policy %I on %I.%I;', old.name, old.schema, old.table));
+end
+$$;`
+ return { sql }
+}
+
+export default {
+ list,
+ retrieve,
+ create,
+ update,
+ remove,
+ zod: pgPolicyZod,
+}
diff --git a/packages/pg-meta/src/sql/policies.ts b/packages/pg-meta/src/sql/policies.ts
new file mode 100644
index 00000000000..66ff548ed8f
--- /dev/null
+++ b/packages/pg-meta/src/sql/policies.ts
@@ -0,0 +1,35 @@
+export const POLICIES_SQL = /* SQL */ `
+select
+ pol.oid :: int8 as id,
+ n.nspname as schema,
+ c.relname as table,
+ c.oid :: int8 as table_id,
+ pol.polname as name,
+ case
+ when pol.polpermissive then 'PERMISSIVE'::text
+ else 'RESTRICTIVE'::text
+ end as action,
+ case
+ when pol.polroles = '{0}'::oid[] then array_to_json(string_to_array('public'::text, ''::text)::name[])
+ else array_to_json(array(
+ select pg_roles.rolname
+ from pg_roles
+ where pg_roles.oid = any(pol.polroles)
+ order by pg_roles.rolname
+ ))
+ end as roles,
+ case pol.polcmd
+ when 'r'::"char" then 'SELECT'::text
+ when 'a'::"char" then 'INSERT'::text
+ when 'w'::"char" then 'UPDATE'::text
+ when 'd'::"char" then 'DELETE'::text
+ when '*'::"char" then 'ALL'::text
+ else null::text
+ end as command,
+ pg_get_expr(pol.polqual, pol.polrelid) as definition,
+ pg_get_expr(pol.polwithcheck, pol.polrelid) as check
+from
+ pg_policy pol
+ join pg_class c on c.oid = pol.polrelid
+ left join pg_namespace n on n.oid = c.relnamespace
+`
diff --git a/packages/pg-meta/test/policies.test.ts b/packages/pg-meta/test/policies.test.ts
new file mode 100644
index 00000000000..9ac252ca1d3
--- /dev/null
+++ b/packages/pg-meta/test/policies.test.ts
@@ -0,0 +1,145 @@
+import { expect, test } from 'vitest'
+import pgMeta from '../src/index'
+import { createTestDatabase, cleanupRoot } from './db/utils'
+import { afterAll } from 'vitest'
+
+afterAll(async () => {
+ await cleanupRoot()
+})
+
+const withTestDatabase = (
+ name: string,
+ fn: (db: Awaited<ReturnType<typeof createTestDatabase>>) => Promise<void>
+) => {
+ test(name, async () => {
+ const db = await createTestDatabase()
+ try {
+ await fn(db)
+ } finally {
+ await db.cleanup()
+ }
+ })
+}
+
+withTestDatabase('list policies', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.policies.list()
+ const res = zod.parse(await executeQuery(sql))
+ const policy = res.find(({ name }) => name === 'categories_update_policy')
+
+ expect(policy).toMatchInlineSnapshot(
+ { id: expect.any(Number), table_id: expect.any(Number) },
+ `
+ {
+ "action": "PERMISSIVE",
+ "check": null,
+ "command": "UPDATE",
+ "definition": "(current_setting('my.username'::text) = name)",
+ "id": Any<Number>,
+ "name": "categories_update_policy",
+ "roles": [
+ "postgres",
+ ],
+ "schema": "public",
+ "table": "category",
+ "table_id": Any<Number>,
+ }
+ `
+ )
+})
+
+withTestDatabase('list policies with included schemas', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.policies.list({
+ includedSchemas: ['public'],
+ })
+ const res = zod.parse(await executeQuery(sql))
+
+ expect(res.length).toBeGreaterThan(0)
+ res.forEach((policy) => {
+ expect(policy.schema).toBe('public')
+ })
+})
+
+withTestDatabase('retrieve, create, update, delete policies', async ({ executeQuery }) => {
+ // Create policy
+ const { sql: createSql } = await pgMeta.policies.create({
+ name: 'test_policy',
+ schema: 'public',
+ table: 'memes',
+ action: 'RESTRICTIVE',
+ })
+ await executeQuery(createSql)
+
+ // List to get the created policy
+ const { sql: listSql, zod: listZod } = await pgMeta.policies.list()
+ const policies = listZod.parse(await executeQuery(listSql))
+ const createdPolicy = policies.find((p) => p.name === 'test_policy')
+
+ expect(createdPolicy).toMatchInlineSnapshot(
+ { id: expect.any(Number), table_id: expect.any(Number) },
+ `
+ {
+ "action": "RESTRICTIVE",
+ "check": null,
+ "command": "ALL",
+ "definition": null,
+ "id": Any<Number>,
+ "name": "test_policy",
+ "roles": [
+ "public",
+ ],
+ "schema": "public",
+ "table": "memes",
+ "table_id": Any<Number>,
+ }
+ `
+ )
+
+ // Update policy
+ const { sql: updateSql } = await pgMeta.policies.update(
+ { id: createdPolicy!.id },
+ {
+ name: 'updated_policy',
+ definition: "current_setting('my.username') IN (name)",
+ check: "current_setting('my.username') IN (name)",
+ roles: ['postgres'],
+ }
+ )
+ await executeQuery(updateSql)
+
+ // Retrieve updated policy
+ const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.policies.retrieve({
+ id: createdPolicy!.id,
+ })
+ const updatedPolicy = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+
+ expect(updatedPolicy).toMatchInlineSnapshot(
+ { id: expect.any(Number), table_id: expect.any(Number) },
+ `
+ {
+ "action": "RESTRICTIVE",
+ "check": "(current_setting('my.username'::text) = name)",
+ "command": "ALL",
+ "definition": "(current_setting('my.username'::text) = name)",
+ "id": Any<Number>,
+ "name": "updated_policy",
+ "roles": [
+ "postgres",
+ ],
+ "schema": "public",
+ "table": "memes",
+ "table_id": Any<Number>,
+ }
+ `
+ )
+
+ // Remove policy
+ const { sql: removeSql } = await pgMeta.policies.remove({ id: updatedPolicy!.id })
+ await executeQuery(removeSql)
+
+ // Verify policy is removed
+ const { sql: verifyRemoveSql } = await pgMeta.policies.retrieve({
+ id: updatedPolicy!.id,
+ })
+ const result = await executeQuery(verifyRemoveSql)
+ expect(result).toHaveLength(0)
+})