Files
supabase/packages/pg-meta/test/roles.test.ts
39b359a70e chore: keep db partner roles out of picker (#54019)
## Problem

Newly added trusted partner roles appear as user selectable /
manageable. Resolves DEPR-735.

## Solution

Trusted partner roles should not be selectable in temporary access. And
should not appear as modifiable in the database roles tab.

| Before | After |
| --- | --- |
| <img width="553" height="398" alt="CleanShot 2026-11-27 at 12 24 43"
src="https://github.com/user-attachments/assets/14affc16-2f00-496f-a124-d918acd93bf0"
/> | <img width="553" height="363" alt="CleanShot 2026-11-27 at 12 25
00"
src="https://github.com/user-attachments/assets/de06002f-d063-453e-a9da-00eee8e0616d"
/> |
| _This partner role `this_is_a_test` shouldn’t be here._ | _Partner
role `this_is_a_test` is no longer in the list of options._ |
| <img width="940" height="305" alt="CleanShot 2026-11-30 at 10 34 52"
src="https://github.com/user-attachments/assets/bdface9f-b3f4-4620-b567-cba8d829205e"
/> | <img width="935" height="299" alt="CleanShot 2026-11-30 at 10 37
40"
src="https://github.com/user-attachments/assets/da1abaa3-5a98-4837-9e8f-35be84b6be4c"
/> |
| _Previous definition._ | _Broadened definition to better encompass
roles we generally manage
([context](https://github.com/supabase/supabase/pull/54019#discussion_r4716757425))._
|

## How to test

1. Open the [Studio staging
preview](https://studio-staging-git-chore-depr-735-supabase.vercel.app)
and select a staging test project. If **Temporary access** is off in
**Feature previews**, enable it there. Then go to **Database → Settings
→ Temporary access** and make sure it is enabled for the test project.
2. Go to **Database → Roles**. Open Chrome DevTools, select **Network**,
and reload. Filter for `key=database-roles`. Right-click the matching
request and select **Override content**.
3. Append this test role to the roles array. Save the override and
reload.

```json
{
  "id": 99999,
  "name": "this_is_a_test",
  "isSuperuser": false,
  "canCreateDb": false,
  "canCreateRole": false,
  "inheritRole": true,
  "canLogin": true,
  "isReplicationRole": false,
  "canBypassRls": false,
  "activeConnections": 0,
  "connectionLimit": 90,
  "validUntil": null,
  "comment": "{\"_supabase\":{\"oauth_app_id\":\"app\"}}",
  "config": {}
}
```

4. In **Database → Roles**, make sure that `this_is_a_test` appears
under **Supabase managed roles** without edit or delete controls.
5. Go to **Database → Settings → Temporary access**, select **Add
rule**, and open the role picker. The test role should be absent.
6. Set the test role's `comment` to `null` in the override and reload.
Open **Add rule** again and make sure that the role is now selectable.
Close the form without saving and remove the override.

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
Co-authored-by: Danny White <3104761+dnywh@users.noreply.github.com>
2026-11-30 15:35:30 +01:00

374 lines
12 KiB
TypeScript

import { randomUUID } from 'node:crypto'
import { afterAll, beforeAll, expect, test } from 'vitest'
import pgMeta, { ident, literal, safeSql } from '../src/index'
import { cleanupRoot, createTestDatabase } from './db/utils'
beforeAll(async () => {
// Any global setup if needed
})
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 roles', async ({ executeQuery }) => {
const { sql, zod } = await pgMeta.roles.list()
const res = zod.parse(await executeQuery(sql))
let role = res.find(({ name }) => name === 'postgres')
expect(role).toMatchInlineSnapshot(
{ activeConnections: expect.any(Number), id: expect.any(Number) },
`
{
"activeConnections": Any<Number>,
"canBypassRls": true,
"canCreateDb": true,
"canCreateRole": true,
"canLogin": true,
"comment": null,
"config": {},
"connectionLimit": 100,
"id": Any<Number>,
"inheritRole": true,
"isReplicationRole": true,
"isSuperuser": true,
"name": "postgres",
"validUntil": null,
}
`
)
// pg_monitor is a predefined role. `includeDefaultRoles` defaults to false,
// so it shouldn't be included in the result.
role = res.find(({ name }) => name === 'pg_monitor')
expect(role).toMatchInlineSnapshot(`undefined`)
})
withTestDatabase('list roles w/ default roles', async ({ executeQuery }) => {
const { sql, zod } = await pgMeta.roles.list({ includeDefaultRoles: true })
const res = zod.parse(await executeQuery(sql))
const role = res.find(({ name }) => name === 'pg_monitor')
expect(role).toMatchInlineSnapshot(
{
activeConnections: expect.any(Number),
id: expect.any(Number),
},
`
{
"activeConnections": Any<Number>,
"canBypassRls": false,
"canCreateDb": false,
"canCreateRole": false,
"canLogin": false,
"comment": null,
"config": {},
"connectionLimit": 100,
"id": Any<Number>,
"inheritRole": true,
"isReplicationRole": false,
"isSuperuser": false,
"name": "pg_monitor",
"validUntil": null,
}
`
)
})
withTestDatabase('retrieve, create, update, delete roles', async ({ executeQuery }) => {
// Create role
const { sql: createSql } = pgMeta.roles.create({
name: 'r1',
isSuperuser: true,
canCreateDb: true,
canCreateRole: true,
inheritRole: false,
canLogin: true,
isReplicationRole: true,
canBypassRls: true,
connectionLimit: 100,
validUntil: '2020-01-01T00:00:00.000Z',
config: { search_path: 'extension, public' },
})
await executeQuery(createSql)
// Retrieve the created role using list
const { sql: listSql, zod: listZod } = await pgMeta.roles.list()
const roles = listZod.parse(await executeQuery(listSql))
const createdRole = roles.find((role) => role.name === 'r1')
expect(createdRole).toMatchInlineSnapshot(
{ id: expect.any(Number), activeConnections: expect.any(Number) },
`
{
"activeConnections": Any<Number>,
"canBypassRls": true,
"canCreateDb": true,
"canCreateRole": true,
"canLogin": true,
"comment": null,
"config": {
"search_path": ""extension, public"",
},
"connectionLimit": 100,
"id": Any<Number>,
"inheritRole": false,
"isReplicationRole": true,
"isSuperuser": true,
"name": "r1",
"validUntil": "2020-01-01 00:00:00+00",
}
`
)
// Remove role
const { sql: removeSql } = pgMeta.roles.remove({ id: createdRole!.id })
await executeQuery(removeSql)
// Create a new role for update test
const { sql: createNewSql } = pgMeta.roles.create({
name: 'r1',
})
await executeQuery(createNewSql)
// Get the role ID for update
const { sql: getIdSql, zod: getIdZod } = await pgMeta.roles.list()
const roleForUpdate = getIdZod
.parse(await executeQuery(getIdSql))
.find((role) => role.name === 'r1')
// Update role with ISO string date
const { sql: updateSql } = pgMeta.roles.update(
{ id: roleForUpdate!.id },
{
name: 'rr',
isSuperuser: true,
canCreateDb: true,
canCreateRole: true,
inheritRole: false,
canLogin: true,
isReplicationRole: true,
canBypassRls: true,
connectionLimit: 100,
validUntil: '2020-01-01T00:00:00.000Z',
}
)
await executeQuery(updateSql)
// Verify update using retrieve
const { sql: retrieveUpdatedSql, zod: retrieveZod } = pgMeta.roles.retrieve({
id: roleForUpdate!.id,
})
const updatedRole = retrieveZod.parse((await executeQuery(retrieveUpdatedSql))[0])
expect(updatedRole).toMatchInlineSnapshot(
{ id: expect.any(Number), activeConnections: expect.any(Number) },
`
{
"activeConnections": Any<Number>,
"canBypassRls": true,
"canCreateDb": true,
"canCreateRole": true,
"canLogin": true,
"comment": null,
"config": {},
"connectionLimit": 100,
"id": Any<Number>,
"inheritRole": false,
"isReplicationRole": true,
"isSuperuser": true,
"name": "rr",
"validUntil": "2020-01-01 00:00:00+00",
}
`
)
// Create role with config
const { sql: createConfigSql } = pgMeta.roles.create({
name: 'config_role',
config: { search_path: 'public', log_statement: 'all' },
})
await executeQuery(createConfigSql)
// Verify config role using list
const { sql: listConfigSql, zod: listConfigZod } = await pgMeta.roles.list()
const configRole = listConfigZod
.parse(await executeQuery(listConfigSql))
.find((role) => role.name === 'config_role')
expect(configRole).toMatchInlineSnapshot(
{ id: expect.any(Number), activeConnections: expect.any(Number) },
`
{
"activeConnections": Any<Number>,
"canBypassRls": false,
"canCreateDb": false,
"canCreateRole": false,
"canLogin": false,
"comment": null,
"config": {
"log_statement": "all",
"search_path": "public",
},
"connectionLimit": 100,
"id": Any<Number>,
"inheritRole": true,
"isReplicationRole": false,
"isSuperuser": false,
"name": "config_role",
"validUntil": null,
}
`
)
// Remove role and verify it's gone
const { sql: finalRemoveSql } = pgMeta.roles.remove({ id: configRole!.id })
await executeQuery(finalRemoveSql)
const { sql: finalListSql, zod: finalListZod } = await pgMeta.roles.list()
const finalRoles = finalListZod.parse(await executeQuery(finalListSql))
expect(finalRoles.find((role) => role.name === 'config_role')).toBeUndefined()
})
withTestDatabase('update and remove a role whose name needs quoting', async ({ executeQuery }) => {
const { sql: createSql } = pgMeta.roles.create({ name: 'quoting_r1' })
await executeQuery(createSql)
const { sql: listSql, zod: listZod } = pgMeta.roles.list()
const findRole = async (name: string) =>
listZod.parse(await executeQuery(listSql)).find((role) => role.name === name)
const { id } = (await findRole('quoting_r1'))!
// The rename and `valid until %L` are separate statements in one `do` block.
await executeQuery(
pgMeta.roles.update(
{ id },
{ name: `it's a "role"`, canLogin: true, validUntil: '2030-01-01T00:00:00.000Z' }
).sql
)
const renamed = (await findRole(`it's a "role"`))!
expect(await findRole('quoting_r1')).toBeUndefined()
expect(renamed.id).toBe(id)
expect(renamed.canLogin).toBe(true)
// The server's time zone decides how the value is printed, so compare instants.
expect(new Date(renamed.validUntil!).toISOString()).toBe('2030-01-01T00:00:00.000Z')
await executeQuery(pgMeta.roles.remove({ id }).sql)
expect(await findRole(`it's a "role"`)).toBeUndefined()
})
// Roles are cluster-wide, so the tests below use unique names and only drop a role once
// they've created it. Dropping the test database doesn't remove roles.
const uniqueRoleName = (prefix: string) => `${prefix}_${randomUUID().replace(/-/g, '_')}`
withTestDatabase('update a role password that needs quoting', async ({ executeQuery }) => {
const name = uniqueRoleName('update_pw')
await executeQuery(pgMeta.roles.create({ name }).sql)
try {
const getPassword = async () =>
(
await executeQuery(
safeSql`select rolpassword from pg_authid where rolname = ${literal(name)}`
)
)[0].rolpassword as string | null
expect(await getPassword()).toBeNull()
const seen = new Set<string | null>()
for (const password of ['plain', `it's a "secret"`, '100%s%I%%']) {
await executeQuery(pgMeta.roles.update({ name }, { password }).sql)
const stored = await getPassword()
// Hashes are salted, so assert the password was replaced, not what it hashed to.
expect(stored).not.toBeNull()
expect(seen.has(stored)).toBe(false)
seen.add(stored)
}
} finally {
await executeQuery(safeSql`drop role if exists ${ident(name)}`)
}
})
withTestDatabase('create a role with a password containing quotes', async ({ executeQuery }) => {
// Roles are cluster-wide, so use a unique name and only drop it once it has been created.
const name = `password_${randomUUID().replace(/-/g, '_')}`
await executeQuery(pgMeta.roles.create({ name, canLogin: true, password: `p'ss"word` }).sql)
try {
const rows = await executeQuery(
safeSql`select rolcanlogin, rolpassword is not null as has_password from pg_authid where rolname = ${literal(name)}`
)
expect(rows).toEqual([{ rolcanlogin: true, has_password: true }])
} finally {
await executeQuery(safeSql`drop role if exists ${ident(name)}`)
}
})
withTestDatabase('update a password together with valid until', async ({ executeQuery }) => {
const name = uniqueRoleName('update_pw_until')
await executeQuery(pgMeta.roles.create({ name }).sql)
try {
await executeQuery(
pgMeta.roles.update({ name }, { password: `it's`, validUntil: '2030-01-01T00:00:00.000Z' })
.sql
)
const [row] = await executeQuery(
safeSql`select rolpassword is not null as has_password, rolvaliduntil from pg_authid where rolname = ${literal(name)}`
)
expect(row.has_password).toBe(true)
expect(new Date(row.rolvaliduntil).toISOString()).toBe('2030-01-01T00:00:00.000Z')
} finally {
await executeQuery(safeSql`drop role if exists ${ident(name)}`)
}
})
withTestDatabase('update or remove a role that does not exist', async ({ executeQuery }) => {
await expect(
executeQuery(pgMeta.roles.update({ id: 999999 }, { canLogin: true }).sql)
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: Failed to execute query: Cannot find role with id 999999]`
)
await expect(
executeQuery(pgMeta.roles.update({ name: 'no_such_role' }, { canLogin: true }).sql)
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: Failed to execute query: Cannot find role with name no_such_role]`
)
await expect(
executeQuery(pgMeta.roles.remove({ id: 999999 }).sql)
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: Failed to execute query: Cannot find role with id 999999]`
)
})
withTestDatabase('retrieve a role comment', async ({ executeQuery }) => {
const name = uniqueRoleName('commented')
await executeQuery(pgMeta.roles.create({ name }).sql)
try {
const comment = '{"_supabase":{"oauth_app_id":"app"}}'
await executeQuery(safeSql`comment on role ${ident(name)} is ${literal(comment)}`)
const { sql, zod } = pgMeta.roles.retrieve({ name })
const role = zod.parse((await executeQuery(sql))[0])
expect(role?.comment).toBe(comment)
} finally {
await executeQuery(safeSql`drop role if exists ${ident(name)}`)
}
})