diff --git a/src/rls/index.test.ts b/src/rls/index.test.ts index cf00156..4df2c74 100644 --- a/src/rls/index.test.ts +++ b/src/rls/index.test.ts @@ -42,7 +42,7 @@ describe('loadPolicies - Policy Fetching and Parsing', () => { operator: '=', left: { type: 'column_ref', - table: 'public.users', + table: 'users', column: 'user_id', }, right: { @@ -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, @@ -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, @@ -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, @@ -130,7 +143,7 @@ describe('applyRLS - Query Modification', () => { config: mockConfig, }) - expect(modifiedSql).toContain("VALUES (1,'Alice')") + expect(modifiedSql).toContain("VALUES ('user123','Alice')") }) }) @@ -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', @@ -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 () => { @@ -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 () => { @@ -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'") }) }) diff --git a/src/rls/index.ts b/src/rls/index.ts index 68abb4e..286ecc1 100644 --- a/src/rls/index.ts +++ b/src/rls/index.ts @@ -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('`')) @@ -84,10 +93,10 @@ export async function loadPolicies(dataSource: DataSource): Promise { // 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 @@ -234,7 +243,7 @@ function applyRLSToAst(ast: any): void { const tablesWithRules: Record = {} policies.forEach((policy) => { - const tbl = normalizeIdentifier(policy.condition.left.table) + const tbl = baseTableName(policy.condition.left.table) if (!tablesWithRules[tbl]) { tablesWithRules[tbl] = [] } @@ -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 [] }) || [] } @@ -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