Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions src/rls/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ describe('loadPolicies - Policy Fetching and Parsing', () => {
operator: '=',
left: {
type: 'column_ref',
table: 'public.users',
table: 'users',
column: 'user_id',
},
right: {
Expand Down Expand Up @@ -95,9 +95,12 @@ describe('applyRLS - Query Modification', () => {
})

console.log('Final SQL:', modifiedSql)
expect(modifiedSql).toContain("WHERE `user_id` = 'user123'")
expect(modifiedSql).toContain("WHERE (`users`.`user_id` = 'user123')")
})
it('should modify DELETE queries by adding policy-based WHERE clause', async () => {
vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([
{ actions: 'DELETE', schema: 'public', table: 'users', column: 'user_id', value: 'context.id()', value_type: 'string', operator: '=' },
] as any)
const sql = "DELETE FROM users WHERE name = 'Alice'"
const modifiedSql = await applyRLS({
sql,
Expand All @@ -106,10 +109,15 @@ describe('applyRLS - Query Modification', () => {
config: mockConfig,
})

expect(modifiedSql).toContain("WHERE `name` = 'Alice'")
expect(modifiedSql).toContain("`name` = 'Alice'")
expect(modifiedSql).toContain("AND (`users`.`user_id` = 'user123')")
expect(modifiedSql).toContain("AND (`users`.`user_id` = 'user123')")
})

it('should modify UPDATE queries with additional WHERE clause', async () => {
vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([
{ actions: 'UPDATE', schema: 'public', table: 'users', column: 'user_id', value: 'context.id()', value_type: 'string', operator: '=' },
] as any)
const sql = "UPDATE users SET name = 'Bob' WHERE age = 25"
const modifiedSql = await applyRLS({
sql,
Expand All @@ -118,10 +126,15 @@ describe('applyRLS - Query Modification', () => {
config: mockConfig,
})

expect(modifiedSql).toContain("`name` = 'Bob' WHERE `age` = 25")
expect(modifiedSql).toContain("`name` = 'Bob'")
expect(modifiedSql).toContain("`age` = 25")
expect(modifiedSql).toContain("AND (`users`.`user_id` = 'user123')")
})

it('should modify INSERT queries to enforce column values', async () => {
vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([
{ actions: 'INSERT', schema: 'public', table: 'users', column: 'user_id', value: 'context.id()', value_type: 'string', operator: '=' },
] as any)
const sql = "INSERT INTO users (user_id, name) VALUES (1, 'Alice')"
const modifiedSql = await applyRLS({
sql,
Expand All @@ -130,7 +143,7 @@ describe('applyRLS - Query Modification', () => {
config: mockConfig,
})

expect(modifiedSql).toContain("VALUES (1,'Alice')")
expect(modifiedSql).toContain("VALUES ('user123','Alice')")
})
})

Expand Down Expand Up @@ -164,6 +177,8 @@ describe('applyRLS - Edge Cases', () => {

describe('applyRLS - Multi-Table Queries', () => {
beforeEach(() => {
mockConfig.role = 'client'
mockConfig.role = 'client'
vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([
{
actions: 'SELECT',
Expand Down Expand Up @@ -200,8 +215,8 @@ describe('applyRLS - Multi-Table Queries', () => {
config: mockConfig,
})

expect(modifiedSql).toContain("WHERE `users.user_id` = 'user123'")
expect(modifiedSql).toContain("AND `orders.user_id` = 'user123'")
expect(modifiedSql).toContain("`users`.`user_id` = 'user123'")
expect(modifiedSql).toContain("`orders`.`user_id` = 'user123'")
})

it('should apply RLS policies to multiple tables in a JOIN', async () => {
Expand All @@ -218,8 +233,9 @@ describe('applyRLS - Multi-Table Queries', () => {
config: mockConfig,
})

expect(modifiedSql).toContain("WHERE (users.user_id = 'user123')")
expect(modifiedSql).toContain("AND (orders.user_id = 'user123')")
expect(modifiedSql).toContain("`users`.`user_id` = 'user123'")
expect(modifiedSql).toContain("`orders`.`user_id` = 'user123'")
expect(modifiedSql).toContain('AND')
})

it('should apply RLS policies to subqueries inside FROM clause', async () => {
Expand All @@ -236,6 +252,6 @@ describe('applyRLS - Multi-Table Queries', () => {
config: mockConfig,
})

expect(modifiedSql).toContain("WHERE `users.user_id` = 'user123'")
expect(modifiedSql).toContain("`users`.`user_id` = 'user123'")
})
})
47 changes: 35 additions & 12 deletions src/rls/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,17 @@ let policies: Policy[] = []
// -> I say this because if an error occurs then it would entirely circumvent rules and over-expose data.
// -> If they really don't want any rules to exist, remove this power-up

// Compare table names ignoring any schema qualifier ("public.users" -> "users"),
// since parsed query table refs are frequently unqualified while policies store
// schema-qualified identifiers.
function baseTableName(name: string): string {
const normalized = normalizeIdentifier(name)
if (!normalized) return normalized
return normalized.includes('.') ? normalized.split('.').pop()! : normalized
}

function normalizeIdentifier(name: string): string {
if (!name) return name
if (!name || typeof name !== 'string') return name
if (
(name.startsWith('"') && name.endsWith('"')) ||
(name.startsWith('`') && name.endsWith('`'))
Expand Down Expand Up @@ -84,10 +93,10 @@ export async function loadPolicies(dataSource: DataSource): Promise<Policy[]> {
// value = `${value}::INT`
}

let tableName = row.schema
? `${row.schema}.${row.table}`
: row.table
tableName = normalizeIdentifier(tableName)
// Keep the column reference unqualified: matching against query table
// refs is schema-aware via baseTableName, and qualified column refs
// (public.users.user_id) render invalid SQL on unaliased tables.
const tableName = normalizeIdentifier(row.table)
const columnName = normalizeIdentifier(row.column)

// If the policy value is context.id(), use a placeholder
Expand Down Expand Up @@ -234,7 +243,7 @@ function applyRLSToAst(ast: any): void {

const tablesWithRules: Record<string, string[]> = {}
policies.forEach((policy) => {
const tbl = normalizeIdentifier(policy.condition.left.table)
const tbl = baseTableName(policy.condition.left.table)
if (!tablesWithRules[tbl]) {
tablesWithRules[tbl] = []
}
Expand Down Expand Up @@ -264,12 +273,26 @@ function applyRLSToAst(ast: any): void {
} else {
// SELECT or DELETE
tables =
ast.from?.map((fromTable: any) => {
let tableName = normalizeIdentifier(fromTable.table)
if (tableName.includes('.')) {
tableName = tableName.split('.')[1]
ast.from?.flatMap((fromTable: any) => {
// Plain table reference
if (fromTable?.table) {
let tableName = normalizeIdentifier(fromTable.table)
if (tableName.includes('.')) {
tableName = tableName.split('.')[1]
}
return [tableName]
}
return tableName
// Derived table (subquery in FROM): recurse into its AST so
// policies apply inside the subquery as well.
const sub =
fromTable?.subquery ??
fromTable?.expr?.ast ??
fromTable?.expr?.select?.ast ??
(fromTable?.expr?.select && typeof fromTable.expr.select === 'object'
? fromTable.expr.select
: undefined)
if (sub) applyRLSToAst(sub)
return []
}) || []
}

Expand All @@ -291,7 +314,7 @@ function applyRLSToAst(ast: any): void {
(policy) => policy.action === statementType || policy.action === '*'
)
.forEach(({ action, condition }) => {
const targetTable = normalizeIdentifier(condition.left.table)
const targetTable = baseTableName(condition.left.table)
const isTargetTable = tables.includes(targetTable)

if (!isTargetTable) return
Expand Down