From 24555f3517b42c6d3540432054c22221124755e9 Mon Sep 17 00:00:00 2001 From: dungfundopt Date: Fri, 20 Nov 2026 17:44:23 +0700 Subject: [PATCH] test: raise Vitest coverage above 75% across all metrics and fix RLS AST tests (#71) --- src/allowlist/index.test.ts | 182 ++++++++++++++++++++++ src/do.test.ts | 169 ++++++++++++++++++++- src/handler.test.ts | 86 +++++++++++ src/import/csv.test.ts | 236 +++++++++++++++++++++++++++++ src/index.test.ts | 285 +++++++++++++++++++++++++++++++++++ src/operation.test.ts | 293 ++++++++++++++++++++++++++++++++++++ src/rls/index.test.ts | 187 +++++++++++++++++++++-- src/rls/index.ts | 30 ++-- 8 files changed, 1443 insertions(+), 25 deletions(-) create mode 100644 src/allowlist/index.test.ts create mode 100644 src/import/csv.test.ts create mode 100644 src/index.test.ts diff --git a/src/allowlist/index.test.ts b/src/allowlist/index.test.ts new file mode 100644 index 0000000..9f70139 --- /dev/null +++ b/src/allowlist/index.test.ts @@ -0,0 +1,182 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { isQueryAllowed } from './index' +import { DataSource } from '../types' +import { StarbaseDBConfiguration } from '../handler' + +describe('Allowlist - isQueryAllowed', () => { + let mockDataSource: DataSource + let clientConfig: StarbaseDBConfiguration + + beforeEach(() => { + vi.restoreAllMocks() + mockDataSource = { + source: 'internal', + rpc: { + executeQuery: vi.fn(), + }, + } as unknown as DataSource + + clientConfig = { + role: 'client', + features: { allowlist: true }, + } + }) + + it('should allow any query when allowlist feature is disabled', async () => { + const result = await isQueryAllowed({ + sql: 'DROP TABLE users', + isEnabled: false, + dataSource: mockDataSource, + config: clientConfig, + }) + + expect(result).toBe(true) + expect(mockDataSource.rpc.executeQuery).not.toHaveBeenCalled() + }) + + it('should bypass allowlist checks for admin role', async () => { + const result = await isQueryAllowed({ + sql: 'SELECT * FROM secrets', + isEnabled: true, + dataSource: mockDataSource, + config: { role: 'admin', features: { allowlist: true } }, + }) + + expect(result).toBe(true) + expect(mockDataSource.rpc.executeQuery).not.toHaveBeenCalled() + }) + + it('should return an Error instance when SQL is empty', async () => { + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([]) + + const result = await isQueryAllowed({ + sql: '', + isEnabled: true, + dataSource: mockDataSource, + config: clientConfig, + }) + + expect(result).toBeInstanceOf(Error) + expect((result as Error).message).toBe( + 'No SQL provided for allowlist check' + ) + }) + + it('should allow matching queries regardless of trailing semicolon or whitespace', async () => { + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([ + { + sql_statement: 'SELECT id, name FROM users WHERE id = 1', + source: 'internal', + }, + { + sql_statement: 'SELECT * FROM ignored_table', + source: 'external', + }, + ]) + + const result = await isQueryAllowed({ + sql: ' SELECT id, name FROM users WHERE id = 1; ', + isEnabled: true, + dataSource: mockDataSource, + config: clientConfig, + }) + + expect(result).toBe(true) + }) + + it('should reject non-matching queries and record them in tmp_allowlist_rejections', async () => { + vi.mocked(mockDataSource.rpc.executeQuery) + .mockResolvedValueOnce([ + { + sql_statement: 'SELECT id FROM users', + source: 'internal', + }, + ]) + .mockResolvedValueOnce([{ sql_statement: 'SELECT * FROM secrets' }]) + + await expect( + isQueryAllowed({ + sql: 'SELECT * FROM secrets', + isEnabled: true, + dataSource: mockDataSource, + config: clientConfig, + }) + ).rejects.toThrow('Query not allowed') + + expect(mockDataSource.rpc.executeQuery).toHaveBeenCalledWith({ + sql: 'INSERT INTO tmp_allowlist_rejections (sql_statement, source) VALUES (?, ?)', + params: ['SELECT * FROM secrets', 'internal'], + }) + }) + + it('should reject when query AST differs in array length, object keys, or primitive values', async () => { + vi.mocked(mockDataSource.rpc.executeQuery) + .mockResolvedValueOnce([ + { + sql_statement: 'SELECT id, name FROM users WHERE id = 1', + source: 'internal', + }, + ]) + .mockResolvedValueOnce([]) + + await expect( + isQueryAllowed({ + sql: 'SELECT id FROM users WHERE id = 1', + isEnabled: true, + dataSource: mockDataSource, + config: clientConfig, + }) + ).rejects.toThrow('Query not allowed') + + vi.mocked(mockDataSource.rpc.executeQuery) + .mockResolvedValueOnce([ + { + sql_statement: 'SELECT id FROM users WHERE id = 1', + source: 'internal', + }, + ]) + .mockResolvedValueOnce([]) + + await expect( + isQueryAllowed({ + sql: 'SELECT id FROM users WHERE id = 2', + isEnabled: true, + dataSource: mockDataSource, + config: clientConfig, + }) + ).rejects.toThrow('Query not allowed') + }) + + it('should handle errors when loading allowlist or recording rejections gracefully', async () => { + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + vi.mocked(mockDataSource.rpc.executeQuery) + .mockRejectedValueOnce(new Error('DB load failure')) + .mockRejectedValueOnce(new Error('DB insert failure')) + + await expect( + isQueryAllowed({ + sql: 'SELECT 1', + isEnabled: true, + dataSource: mockDataSource, + config: clientConfig, + }) + ).rejects.toThrow('Query not allowed') + + expect(consoleErrorSpy).toHaveBeenCalled() + }) + + it('should throw when invalid SQL fails parsing', async () => { + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([]) + + await expect( + isQueryAllowed({ + sql: 'NOT VALID SQL ???', + isEnabled: true, + dataSource: mockDataSource, + config: clientConfig, + }) + ).rejects.toThrow() + }) +}) diff --git a/src/do.test.ts b/src/do.test.ts index 272c4e9..102bc2a 100644 --- a/src/do.test.ts +++ b/src/do.test.ts @@ -59,7 +59,11 @@ global.Response = class { } const mockStorage = { + getAlarm: vi.fn().mockResolvedValue(12345), + setAlarm: vi.fn().mockResolvedValue(undefined), + deleteAlarm: vi.fn().mockResolvedValue(undefined), sql: { + databaseSize: 4096, exec: vi.fn().mockReturnValue({ columnNames: ['id', 'name'], raw: vi.fn().mockReturnValue([ @@ -81,7 +85,7 @@ const mockDurableObjectState = { getTags: vi.fn().mockReturnValue(['session-123']), } as any -const mockEnv = {} as any +const mockEnv = { CLIENT_AUTHORIZATION_TOKEN: 'client-token' } as any let instance: StarbaseDBDurableObject @@ -144,5 +148,168 @@ describe('StarbaseDBDurableObject Tests', () => { await expect( instance.executeQuery({ sql: 'INVALID QUERY' }) ).rejects.toThrow('Query failed') + consoleErrorSpy.mockRestore() + }) + + it('should execute raw queries and parameterized queries', async () => { + const rawResult = await instance.executeQuery({ + sql: 'SELECT * FROM users WHERE id = ?', + params: [1], + isRaw: true, + }) + expect(mockStorage.sql.exec).toHaveBeenCalledWith( + 'SELECT * FROM users WHERE id = ?', + 1 + ) + expect(rawResult).toEqual({ + columns: ['id', 'name'], + rows: [ + [1, 'Alice'], + [2, 'Bob'], + ], + meta: { rows_read: 2, rows_written: 1 }, + }) + }) + + it('should propagate errors from executeTransaction', async () => { + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + mockStorage.sql.exec.mockImplementationOnce(() => { + throw new Error('Tx failed') + }) + await expect( + instance.executeTransaction([{ sql: 'BAD' }], false) + ).rejects.toThrow('Tx failed') + consoleErrorSpy.mockRestore() + }) + + it('should expose init RPC bindings and manage alarms', async () => { + const rpc = instance.init() + expect(await rpc.getAlarm()).toBe(12345) + + await rpc.setAlarm(Date.now() - 5000) + expect(mockStorage.setAlarm).toHaveBeenCalled() + + await rpc.setAlarm(new Date(Date.now() + 60_000)) + expect(mockStorage.setAlarm).toHaveBeenCalledTimes(2) + + await rpc.deleteAlarm() + expect(mockStorage.deleteAlarm).toHaveBeenCalled() + }) + + it('should handle setAlarm errors', async () => { + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + mockStorage.setAlarm.mockRejectedValueOnce(new Error('alarm failed')) + await expect(instance.setAlarm(Date.now() + 5000)).rejects.toThrow( + 'alarm failed' + ) + consoleErrorSpy.mockRestore() + }) + + it('should run alarm callback for active cron tasks and schedule recovery on failure', async () => { + const fetchSpy = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(new Response('ok') as any) + .mockRejectedValueOnce(new Error('callback down')) + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + + mockStorage.sql.exec.mockReturnValueOnce({ + toArray: () => [], + }) + await instance.alarm() + expect(fetchSpy).not.toHaveBeenCalled() + + mockStorage.sql.exec.mockReturnValueOnce({ + toArray: () => [ + { id: 1, callback_host: 'https://worker.example.com' }, + ], + }) + await instance.alarm() + expect(fetchSpy).toHaveBeenCalledWith( + 'https://worker.example.com/cron/callback', + expect.objectContaining({ method: 'POST' }) + ) + + mockStorage.sql.exec.mockReturnValueOnce({ + toArray: () => [ + { id: 1, callback_host: 'https://worker.example.com' }, + ], + }) + await instance.alarm() + expect(mockStorage.setAlarm).toHaveBeenCalled() + + mockStorage.sql.exec.mockImplementationOnce(() => { + throw new Error('DB query failed in alarm') + }) + await instance.alarm() + expect(mockStorage.setAlarm).toHaveBeenCalledTimes(2) + + fetchSpy.mockRestore() + consoleErrorSpy.mockRestore() + }) + + it('should return database statistics', async () => { + mockStorage.sql.exec.mockReturnValueOnce({ + toArray: () => [{ count: 7 }], + }) + const stats = await instance.getStatistics() + expect(stats).toEqual({ + databaseSize: 4096, + activeConnections: 0, + recentQueries: 7, + }) + }) + + it('should handle /socket upgrade, non-websocket /socket, /socket/broadcast, and webSocketMessage/Close', async () => { + const badSocketRes = await instance.fetch( + new Request('https://example.com/socket') + ) + expect(badSocketRes.status).toBe(400) + + const wsRes = await instance.fetch( + new Request('https://example.com/socket?sessionId=s1', { + headers: { upgrade: 'websocket' }, + }) + ) + expect(wsRes.status).toBe(101) + expect(instance.connections.has('s1')).toBe(true) + + const serverWs = instance.connections.get('s1')! + await instance.webSocketMessage( + serverWs, + JSON.stringify({ action: 'query', sql: 'SELECT 1', params: [] }) + ) + expect(serverWs.send).toHaveBeenCalled() + + const bcastRes = await instance.fetch( + new Request('https://example.com/socket/broadcast?sessionId=s1', { + method: 'POST', + body: JSON.stringify({ event: 'ping' }), + }) + ) + expect(bcastRes.status).toBe(200) + + const otherWs = new global.WebSocket('ws://localhost') + otherWs.send = vi.fn(() => { + throw new Error('dead socket') + }) + instance.connections.set('s2', otherWs) + await instance.fetch( + new Request('https://example.com/socket/broadcast', { + method: 'POST', + body: JSON.stringify({ event: 'all' }), + }) + ) + expect(instance.connections.has('s2')).toBe(false) + ;(instance as any).ctx = mockDurableObjectState + instance.connections.set('session-123', serverWs) + await instance.webSocketClose(serverWs, 1000, 'bye', true) + expect(serverWs.close).toHaveBeenCalled() + expect(instance.connections.has('session-123')).toBe(false) }) }) diff --git a/src/handler.test.ts b/src/handler.test.ts index 86bb328..f3bf5c9 100644 --- a/src/handler.test.ts +++ b/src/handler.test.ts @@ -198,5 +198,91 @@ describe('StarbaseDB Error Handling', () => { const response = await instance.queryRoute(request, false) expect(response.status).toBe(500) + consoleErrorSpy.mockRestore() + }) + + it('should throw when external source is configured without external details', () => { + expect( + () => + new StarbaseDB({ + dataSource: { source: 'external', rpc: {} as any }, + config: mockConfig, + }) + ).toThrow('No external data sources available.') + }) + + it('should reject non-JSON Content-Type, invalid params, and invalid transaction entries', async () => { + const badCt = await instance.queryRoute( + new Request('https://example.com/query', { + method: 'POST', + headers: { 'Content-Type': 'text/plain' }, + body: 'SELECT 1', + }), + false + ) + expect(badCt.status).toBe(400) + + const badParams = await instance.queryRoute( + new Request('https://example.com/query', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ sql: 'SELECT 1', params: 'not-valid' }), + }), + false + ) + expect(badParams.status).toBe(400) + + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + + const badTxSql = await instance.queryRoute( + new Request('https://example.com/query', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ transaction: [{ sql: ' ' }] }), + }), + false + ) + expect(badTxSql.status).toBe(500) + + const badTxParams = await instance.queryRoute( + new Request('https://example.com/query', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + transaction: [{ sql: 'SELECT 1', params: 123 }], + }), + }), + false + ) + expect(badTxParams.status).toBe(500) + consoleErrorSpy.mockRestore() + }) + + it('should route matching authless plugin requests in handlePreAuth and skip auth-required plugins', async () => { + const authlessPlugin: any = { + name: 'public-hook', + pathPrefix: '/webhooks/:id/*', + opts: { requiresAuth: false }, + init: vi.fn(), + } + const db = new StarbaseDB({ + dataSource: mockDataSource, + config: mockConfig, + plugins: [authlessPlugin], + }) + + const matched = await db.handlePreAuth( + new Request('https://example.com/webhooks/abc/events'), + mockExecutionContext + ) + expect(matched).toBeDefined() + + const unmatched = await db.handlePreAuth( + new Request('https://example.com/private/data'), + mockExecutionContext + ) + expect(unmatched).toBeUndefined() }) }) diff --git a/src/import/csv.test.ts b/src/import/csv.test.ts new file mode 100644 index 0000000..2d22023 --- /dev/null +++ b/src/import/csv.test.ts @@ -0,0 +1,236 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { importTableFromCsvRoute } from './csv' +import { executeOperation } from '../export' +import { DataSource } from '../types' +import { StarbaseDBConfiguration } from '../handler' + +vi.mock('../export', () => ({ + executeOperation: vi.fn(), +})) + +describe('CSV Import Route - importTableFromCsvRoute', () => { + const mockDataSource = { source: 'internal' } as DataSource + const mockConfig: StarbaseDBConfiguration = { role: 'admin' } + + beforeEach(() => { + vi.clearAllMocks() + }) + + it('should return 400 when request body is empty', async () => { + const request = new Request('http://localhost/import/csv/users', { + method: 'POST', + headers: { 'Content-Type': 'text/csv' }, + }) + + const response = await importTableFromCsvRoute( + 'users', + request, + mockDataSource, + mockConfig + ) + const json: any = await response.json() + + expect(response.status).toBe(400) + expect(json.error).toBe('Request body is empty') + }) + + it('should return 400 for unsupported Content-Type', async () => { + const request = new Request('http://localhost/import/csv/users', { + method: 'POST', + headers: { 'Content-Type': 'text/plain' }, + body: 'id,name\n1,Alice', + }) + + const response = await importTableFromCsvRoute( + 'users', + request, + mockDataSource, + mockConfig + ) + const json: any = await response.json() + + expect(response.status).toBe(400) + expect(json.error).toBe('Unsupported Content-Type') + }) + + it('should import raw text/csv records successfully', async () => { + vi.mocked(executeOperation).mockResolvedValue([]) + const request = new Request('http://localhost/import/csv/users', { + method: 'POST', + headers: { 'Content-Type': 'text/csv' }, + body: 'id,name\n1,Alice\n2,Bob\nincomplete_row', + }) + + const response = await importTableFromCsvRoute( + 'users', + request, + mockDataSource, + mockConfig + ) + const json: any = await response.json() + + expect(response.status).toBe(200) + expect(executeOperation).toHaveBeenCalledTimes(2) + expect(executeOperation).toHaveBeenNthCalledWith( + 1, + [ + { + sql: 'INSERT INTO users (id, name) VALUES (?, ?)', + params: ['1', 'Alice'], + }, + ], + mockDataSource, + mockConfig + ) + expect(json.result.message).toBe( + 'Imported 2 out of 2 records successfully. 0 records failed.' + ) + expect(json.result.failedStatements).toEqual([]) + }) + + it('should import application/json wrapped CSV with columnMapping', async () => { + vi.mocked(executeOperation).mockResolvedValue([]) + const request = new Request('http://localhost/import/csv/users', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + data: 'uid,full_name\n10,Charlie', + columnMapping: { uid: 'id', full_name: 'name' }, + }), + }) + + const response = await importTableFromCsvRoute( + 'users', + request, + mockDataSource, + mockConfig + ) + const json: any = await response.json() + + expect(response.status).toBe(200) + expect(executeOperation).toHaveBeenCalledWith( + [ + { + sql: 'INSERT INTO users (id, name) VALUES (?, ?)', + params: ['10', 'Charlie'], + }, + ], + mockDataSource, + mockConfig + ) + expect(json.result.message).toContain('Imported 1 out of 1') + }) + + it('should import multipart/form-data file upload and reject missing file', async () => { + const emptyForm = new FormData() + const missingFileReq = new Request( + 'http://localhost/import/csv/users', + { + method: 'POST', + body: emptyForm, + } + ) + const missingResp = await importTableFromCsvRoute( + 'users', + missingFileReq, + mockDataSource, + mockConfig + ) + expect(missingResp.status).toBe(400) + expect(((await missingResp.json()) as any).error).toBe( + 'No file uploaded' + ) + + vi.mocked(executeOperation).mockResolvedValue([]) + const form = new FormData() + form.append( + 'file', + new File(['id,name\n7,Dana'], 'users.csv', { type: 'text/csv' }) + ) + const uploadReq = new Request('http://localhost/import/csv/users', { + method: 'POST', + body: form, + }) + const uploadResp = await importTableFromCsvRoute( + 'users', + uploadReq, + mockDataSource, + mockConfig + ) + expect(uploadResp.status).toBe(200) + expect(executeOperation).toHaveBeenCalledTimes(1) + }) + + it('should return 400 when CSV contains only header or no valid rows', async () => { + const request = new Request('http://localhost/import/csv/users', { + method: 'POST', + headers: { 'Content-Type': 'text/csv' }, + body: 'id,name', + }) + + const response = await importTableFromCsvRoute( + 'users', + request, + mockDataSource, + mockConfig + ) + const json: any = await response.json() + + expect(response.status).toBe(400) + expect(json.error).toBe('Invalid CSV format or empty data') + }) + + it('should record failed row inserts without aborting remaining rows', async () => { + vi.mocked(executeOperation) + .mockResolvedValueOnce([]) + .mockRejectedValueOnce(new Error('UNIQUE constraint failed')) + .mockRejectedValueOnce({}) + + const request = new Request('http://localhost/import/csv/users', { + method: 'POST', + headers: { 'Content-Type': 'text/csv' }, + body: 'id,name\n1,Alice\n1,Duplicate\n2,Broken', + }) + + const response = await importTableFromCsvRoute( + 'users', + request, + mockDataSource, + mockConfig + ) + const json: any = await response.json() + + expect(response.status).toBe(200) + expect(json.result.message).toBe( + 'Imported 1 out of 3 records successfully. 2 records failed.' + ) + expect(json.result.failedStatements).toHaveLength(2) + expect(json.result.failedStatements[0].error).toBe( + 'UNIQUE constraint failed' + ) + expect(json.result.failedStatements[1].error).toBe('Unknown error') + }) + + it('should return 500 when JSON payload is malformed', async () => { + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + const request = new Request('http://localhost/import/csv/users', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: '{bad json', + }) + + const response = await importTableFromCsvRoute( + 'users', + request, + mockDataSource, + mockConfig + ) + const json: any = await response.json() + + expect(response.status).toBe(500) + expect(json.error).toContain('Failed to import CSV data:') + consoleErrorSpy.mockRestore() + }) +}) diff --git a/src/index.test.ts b/src/index.test.ts new file mode 100644 index 0000000..090548e --- /dev/null +++ b/src/index.test.ts @@ -0,0 +1,285 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createRemoteJWKSet, jwtVerify } from 'jose' +import { StarbaseDB } from './handler' +import { InterfacePlugin } from '../plugins/interface' +import worker, { Env } from './index' + +vi.mock('./do', () => ({ + StarbaseDBDurableObject: class {}, +})) + +vi.mock('jose', () => ({ + createRemoteJWKSet: vi.fn(() => 'mock-jwks'), + jwtVerify: vi.fn(), +})) + +vi.mock('../plugins/websocket', () => ({ + WebSocketPlugin: vi.fn().mockImplementation(() => ({ + name: 'websocket', + opts: { requiresAuth: true }, + init: vi.fn(), + })), +})) +vi.mock('../plugins/studio', () => ({ + StudioPlugin: vi.fn().mockImplementation(() => ({ + name: 'studio', + opts: { requiresAuth: true }, + init: vi.fn(), + })), +})) +vi.mock('../plugins/sql-macros', () => ({ + SqlMacrosPlugin: vi.fn().mockImplementation(() => ({ + name: 'sql-macros', + opts: { requiresAuth: true }, + init: vi.fn(), + })), +})) +vi.mock('../plugins/cdc', () => ({ + ChangeDataCapturePlugin: vi.fn().mockImplementation(() => ({ + name: 'cdc', + opts: { requiresAuth: true }, + onEvent: vi.fn(), + init: vi.fn(), + })), +})) +vi.mock('../plugins/query-log', () => ({ + QueryLogPlugin: vi.fn().mockImplementation(() => ({ + name: 'query-log', + opts: { requiresAuth: true }, + init: vi.fn(), + })), +})) +vi.mock('../plugins/stats', () => ({ + StatsPlugin: vi.fn().mockImplementation(() => ({ + name: 'stats', + opts: { requiresAuth: true }, + init: vi.fn(), + })), +})) +vi.mock('../plugins/cron', () => ({ + CronPlugin: vi.fn().mockImplementation(() => ({ + name: 'cron', + opts: { requiresAuth: true }, + onEvent: vi.fn(), + init: vi.fn(), + })), +})) +vi.mock('../plugins/interface', () => ({ + InterfacePlugin: vi.fn().mockImplementation(() => ({ + name: 'interface', + opts: { requiresAuth: true }, + matchesRoute: vi.fn(() => false), + init: vi.fn(), + })), +})) + +describe('Worker Entrypoint - fetch', () => { + let mockRpc: any + let mockStub: any + let mockEnv: Env + let mockCtx: ExecutionContext + + beforeEach(() => { + vi.clearAllMocks() + mockRpc = { + executeQuery: vi.fn().mockResolvedValue([]), + getAlarm: vi.fn(), + setAlarm: vi.fn(), + deleteAlarm: vi.fn(), + getStatistics: vi.fn(), + } + mockStub = { + init: vi.fn().mockResolvedValue(mockRpc), + } + mockEnv = { + ADMIN_AUTHORIZATION_TOKEN: 'admin-secret', + CLIENT_AUTHORIZATION_TOKEN: 'client-secret', + REGION: 'auto', + DATABASE_DURABLE_OBJECT: { + idFromName: vi.fn().mockReturnValue('do-id'), + get: vi.fn().mockReturnValue(mockStub), + }, + HYPERDRIVE: undefined, + } as unknown as Env + mockCtx = { + waitUntil: vi.fn(), + passThroughOnException: vi.fn(), + } as unknown as ExecutionContext + + vi.spyOn(StarbaseDB.prototype, 'handlePreAuth').mockResolvedValue( + undefined + ) + vi.spyOn(StarbaseDB.prototype, 'handle').mockResolvedValue( + new Response(JSON.stringify({ result: 'ok' }), { status: 200 }) + ) + }) + + it('should respond to OPTIONS CORS preflight immediately', async () => { + const req = new Request('http://localhost/query', { method: 'OPTIONS' }) + const res = await worker.fetch(req, mockEnv, mockCtx) + expect(res.status).toBe(204) + expect(mockEnv.DATABASE_DURABLE_OBJECT.get).not.toHaveBeenCalled() + }) + + it('should return 401 when Authorization header is missing', async () => { + const req = new Request('http://localhost/query', { method: 'POST' }) + const res = await worker.fetch(req, mockEnv, mockCtx) + const json: any = await res.json() + expect(res.status).toBe(401) + expect(json.error).toBe('Unauthorized request') + }) + + it('should authenticate admin bearer token and use explicit region hint', async () => { + mockEnv.REGION = 'wnam' + const req = new Request('http://localhost/query', { + method: 'POST', + headers: { + Authorization: 'Bearer admin-secret', + 'X-Starbase-Cache': 'true', + }, + }) + const res = await worker.fetch(req, mockEnv, mockCtx) + expect(res.status).toBe(200) + expect(mockEnv.DATABASE_DURABLE_OBJECT.get).toHaveBeenCalledWith( + 'do-id', + { locationHint: 'wnam' } + ) + }) + + it('should authenticate client token via WebSocket query param', async () => { + const req = new Request( + 'http://localhost/ws?token=client-secret&source=internal', + { + headers: { Upgrade: 'websocket' }, + } + ) + const res = await worker.fetch(req, mockEnv, mockCtx) + expect(res.status).toBe(200) + }) + + it('should reject unknown token with 400 when JWKS is not configured', async () => { + const req = new Request('http://localhost/query', { + method: 'POST', + headers: { Authorization: 'Bearer bad-token' }, + }) + const res = await worker.fetch(req, mockEnv, mockCtx) + const json: any = await res.json() + expect(res.status).toBe(400) + expect(json.error).toBe('Unauthorized request') + }) + + it('should authenticate valid JWT via JWKS endpoint and reject missing sub', async () => { + mockEnv.AUTH_JWKS_ENDPOINT = + 'https://auth.example.com/.well-known/jwks.json' + mockEnv.AUTH_ALGORITHM = 'RS256' + vi.mocked(jwtVerify).mockResolvedValueOnce({ + payload: { sub: 'user-42' }, + } as any) + + const okReq = new Request('http://localhost/query', { + method: 'POST', + headers: { Authorization: 'Bearer jwt-token' }, + }) + const okRes = await worker.fetch(okReq, mockEnv, mockCtx) + expect(okRes.status).toBe(200) + expect(createRemoteJWKSet).toHaveBeenCalled() + + vi.mocked(jwtVerify).mockResolvedValueOnce({ payload: {} } as any) + const badReq = new Request('http://localhost/query', { + method: 'POST', + headers: { Authorization: 'Bearer jwt-no-sub' }, + }) + const badRes = await worker.fetch(badReq, mockEnv, mockCtx) + expect(badRes.status).toBe(400) + expect(((await badRes.json()) as any).error).toBe( + 'Invalid JWT payload, subject not found.' + ) + }) + + it('should return pre-auth plugin response without checking bearer token', async () => { + vi.spyOn(StarbaseDB.prototype, 'handlePreAuth').mockResolvedValueOnce( + new Response('preauth-ok', { status: 200 }) + ) + const req = new Request('http://localhost/public') + const res = await worker.fetch(req, mockEnv, mockCtx) + expect(res.status).toBe(200) + expect(await res.text()).toBe('preauth-ok') + }) + + it('should bypass token auth when InterfacePlugin matches route', async () => { + vi.mocked(InterfacePlugin).mockImplementationOnce( + () => + ({ + name: 'interface', + opts: { requiresAuth: true }, + matchesRoute: vi.fn(() => true), + init: vi.fn(), + }) as any + ) + const req = new Request('http://localhost/ui') + const res = await worker.fetch(req, mockEnv, mockCtx) + expect(res.status).toBe(200) + }) + + it('should configure external postgresql, mysql, sqlite providers, and hyperdrive', async () => { + const scenarios: Partial[] = [ + { + EXTERNAL_DB_TYPE: 'postgresql', + EXTERNAL_DB_HOST: 'pg.local', + EXTERNAL_DB_PORT: 5432, + EXTERNAL_DB_USER: 'u', + EXTERNAL_DB_PASS: 'p', + EXTERNAL_DB_DATABASE: 'db', + }, + { + EXTERNAL_DB_TYPE: 'mysql', + EXTERNAL_DB_HOST: 'mysql.local', + EXTERNAL_DB_PORT: 3306, + EXTERNAL_DB_USER: 'u', + EXTERNAL_DB_PASS: 'p', + EXTERNAL_DB_DATABASE: 'db', + }, + { + EXTERNAL_DB_TYPE: 'sqlite', + EXTERNAL_DB_CLOUDFLARE_API_KEY: 'cf-key', + EXTERNAL_DB_CLOUDFLARE_ACCOUNT_ID: 'acc', + EXTERNAL_DB_CLOUDFLARE_DATABASE_ID: 'd1', + EXTERNAL_DB_STARBASEDB_URI: 'https://sb.local', + EXTERNAL_DB_STARBASEDB_TOKEN: 'tok', + EXTERNAL_DB_TURSO_URI: 'libsql://turso.local', + EXTERNAL_DB_TURSO_TOKEN: 'turso-tok', + }, + { + HYPERDRIVE: { + connectionString: 'postgres://user:pass@hd/db', + } as any, + }, + ] + + for (const [idx, extra] of scenarios.entries()) { + const env = { ...mockEnv, ...extra } as Env + const sourceHeader = idx === 3 ? 'hyperdrive' : 'external' + const req = new Request('http://localhost/query', { + method: 'POST', + headers: { + Authorization: 'Bearer admin-secret', + 'X-Starbase-Source': sourceHeader, + }, + }) + const res = await worker.fetch(req, env, mockCtx) + expect(res.status).toBe(200) + } + }) + + it('should return 400 error response when Durable Object init throws', async () => { + mockStub.init.mockRejectedValueOnce(new Error('DO init crashed')) + const req = new Request('http://localhost/query', { + method: 'POST', + headers: { Authorization: 'Bearer admin-secret' }, + }) + const res = await worker.fetch(req, mockEnv, mockCtx) + const json: any = await res.json() + expect(res.status).toBe(400) + expect(json.error).toBe('DO init crashed') + }) +}) diff --git a/src/operation.test.ts b/src/operation.test.ts index f52cbb9..2af3e39 100644 --- a/src/operation.test.ts +++ b/src/operation.test.ts @@ -94,6 +94,42 @@ vi.mock('./cache', () => ({ afterQueryCache: vi.fn(), })) +const mockPgUnsafe = vi.fn() +const mockPgEnd = vi.fn().mockResolvedValue(undefined) +vi.mock('postgres', () => ({ + default: vi.fn(() => ({ + unsafe: mockPgUnsafe, + end: mockPgEnd, + })), +})) + +vi.mock('pg', () => ({ + Client: vi.fn().mockImplementation(() => ({})), +})) +vi.mock('mysql2', () => ({ + createConnection: vi.fn(() => ({})), +})) +vi.mock('@libsql/client/web', () => ({ + createClient: vi.fn(() => ({})), +})) + +const mockSdkConnect = vi.fn().mockResolvedValue(undefined) +const mockSdkRaw = vi.fn().mockResolvedValue({ data: [{ id: 1, name: 'SDK' }] }) +vi.mock('@outerbase/sdk', () => { + const makeConn = () => + vi.fn().mockImplementation(() => ({ + connect: mockSdkConnect, + raw: mockSdkRaw, + })) + return { + PostgreSQLConnection: makeConn(), + MySQLConnection: makeConn(), + TursoConnection: makeConn(), + CloudflareD1Connection: makeConn(), + StarbaseConnection: makeConn(), + } +}) + let mockSqlConnection: SqlConnection let mockDataSource: DataSource let mockConfig: StarbaseDBConfiguration @@ -445,6 +481,263 @@ describe('executeExternalQuery', () => { expect(result).toEqual([]) }) + + it('should delegate to executeSDKQuery when outerbaseApiKey is not set', async () => { + const result = await executeExternalQuery({ + sql: 'SELECT 1', + params: [], + dataSource: mockDataSource, + config: { role: 'admin' }, + }) + expect(mockSdkConnect).toHaveBeenCalled() + expect(result).toEqual([{ id: 1, name: 'SDK' }]) + }) +}) + +describe('executeQuery - raw, hooks, hyperdrive, and external paths', () => { + it('should transform raw results through beforeQuery and afterQuery hooks', async () => { + const beforeQuery = vi.fn(async ({ sql, params }) => ({ + sql: `${sql} -- hooked`, + params, + })) + const afterQuery = vi.fn(async ({ result }) => [ + ...result, + { id: 3, name: 'Hooked' }, + ]) + const ds: DataSource = { + ...mockDataSource, + source: 'internal', + registry: { beforeQuery, afterQuery } as any, + rpc: { + executeQuery: vi.fn().mockResolvedValue({ + columns: ['id', 'name'], + rows: [[1, 'Alice']], + meta: { rows_read: 1, rows_written: 0 }, + }), + } as any, + } + + const res = (await executeQuery({ + sql: 'SELECT id, name FROM users', + params: [], + isRaw: true, + dataSource: ds, + config: mockConfig, + })) as any + + expect(beforeQuery).toHaveBeenCalled() + expect(afterQuery).toHaveBeenCalled() + expect(res.columns).toEqual(['id', 'name']) + expect(res.rows).toHaveLength(2) + }) + + it('should swallow afterQuery hook errors and return original result', async () => { + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + const ds: DataSource = { + ...mockDataSource, + source: 'internal', + registry: { + beforeQuery: vi.fn(async (o) => o), + afterQuery: vi.fn().mockRejectedValue(new Error('hook fail')), + } as any, + } + const res = await executeQuery({ + sql: 'SELECT 1', + params: [], + isRaw: false, + dataSource: ds, + config: mockConfig, + }) + expect(res).toEqual([ + { id: 1, name: 'Alice' }, + { id: 2, name: 'Bob' }, + ]) + consoleErrorSpy.mockRestore() + }) + + it('should return empty array when internal rpc returns nullish', async () => { + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + const ds: DataSource = { + ...mockDataSource, + rpc: { executeQuery: vi.fn().mockResolvedValue(null) } as any, + } + const res = await executeQuery({ + sql: 'SELECT 1', + params: [], + isRaw: false, + dataSource: ds, + config: mockConfig, + }) + expect(res).toEqual([]) + consoleErrorSpy.mockRestore() + }) + + it('should execute hyperdrive queries with and without executionContext and throw on missing connectionString', async () => { + await expect( + executeQuery({ + sql: 'SELECT 1', + params: [], + isRaw: false, + dataSource: { source: 'hyperdrive', rpc: mockDataSource.rpc }, + config: mockConfig, + }) + ).rejects.toThrow('Hyperdrive connection string not found') + + mockPgUnsafe.mockResolvedValueOnce([{ ok: 1 }]) + const waitUntil = vi.fn() + const res1 = await executeQuery({ + sql: 'SELECT 1', + params: [], + isRaw: false, + dataSource: { + source: 'hyperdrive', + external: { + dialect: 'postgresql', + connectionString: 'postgres://hd', + }, + executionContext: { waitUntil } as any, + rpc: mockDataSource.rpc, + }, + config: mockConfig, + }) + expect(res1).toEqual([{ ok: 1 }]) + expect(waitUntil).toHaveBeenCalled() + + mockPgUnsafe.mockResolvedValueOnce([{ ok: 2 }]) + const res2 = await executeQuery({ + sql: 'SELECT 2', + params: [], + isRaw: false, + dataSource: { + source: 'hyperdrive', + external: { + dialect: 'postgresql', + connectionString: 'postgres://hd', + }, + rpc: mockDataSource.rpc, + }, + config: mockConfig, + }) + expect(res2).toEqual([{ ok: 2 }]) + expect(mockPgEnd).toHaveBeenCalled() + + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + mockPgUnsafe.mockRejectedValueOnce(new Error('pg fail')) + await expect( + executeQuery({ + sql: 'SELECT bad', + params: [], + isRaw: false, + dataSource: { + source: 'hyperdrive', + external: { + dialect: 'postgresql', + connectionString: 'postgres://hd', + }, + rpc: mockDataSource.rpc, + }, + config: mockConfig, + }) + ).rejects.toThrow('pg fail') + consoleErrorSpy.mockRestore() + }) + + it('should route external queries through executeQuery', async () => { + const res = await executeQuery({ + sql: 'SELECT 1', + params: [], + isRaw: false, + dataSource: { ...mockDataSource, source: 'external' }, + config: { role: 'admin' }, + }) + expect(res).toEqual([{ id: 1, name: 'SDK' }]) + }) +}) + +describe('executeSDKQuery - all supported external providers', () => { + it('should warn and return empty array when external source is missing', async () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const res = await executeSDKQuery({ + sql: 'SELECT 1', + dataSource: { source: 'external', rpc: mockDataSource.rpc }, + config: mockConfig, + }) + expect(res).toEqual([]) + warnSpy.mockRestore() + }) + + it('should connect using postgresql, mysql, cloudflare-d1, starbase, and turso providers', async () => { + const externals: any[] = [ + { + dialect: 'postgresql', + host: 'h', + port: 5432, + user: 'u', + password: 'p', + database: 'd', + }, + { + dialect: 'mysql', + host: 'h', + port: 3306, + user: 'u', + password: 'p', + database: 'd', + }, + { + dialect: 'sqlite', + provider: 'cloudflare-d1', + apiKey: 'k', + accountId: 'a', + databaseId: 'db', + }, + { + dialect: 'sqlite', + provider: 'starbase', + apiKey: 'k', + token: 't', + }, + { + dialect: 'sqlite', + provider: 'turso', + uri: 'libsql://x', + token: 't', + }, + ] + + for (const ext of externals) { + const res = await executeSDKQuery({ + sql: 'SELECT 1', + dataSource: { + source: 'external', + external: ext, + rpc: mockDataSource.rpc, + }, + config: mockConfig, + }) + expect(res).toEqual([{ id: 1, name: 'SDK' }]) + } + }) + + it('should throw for unsupported external database type', async () => { + await expect( + executeSDKQuery({ + sql: 'SELECT 1', + dataSource: { + source: 'external', + external: { dialect: 'oracle' } as any, + rpc: mockDataSource.rpc, + }, + config: mockConfig, + }) + ).rejects.toThrow('Unsupported external database type') + }) }) // describe('executeSDKQuery', () => { diff --git a/src/rls/index.test.ts b/src/rls/index.test.ts index cf00156..2bae9fa 100644 --- a/src/rls/index.test.ts +++ b/src/rls/index.test.ts @@ -86,6 +86,17 @@ describe('applyRLS - Query Modification', () => { }) it('should modify SELECT queries with WHERE conditions', async () => { + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([ + { + actions: 'SELECT', + schema: '', + table: 'users', + column: 'user_id', + value: 'context.id()', + value_type: 'string', + operator: '=', + }, + ]) const sql = 'SELECT * FROM users' const modifiedSql = await applyRLS({ sql, @@ -94,10 +105,20 @@ describe('applyRLS - Query Modification', () => { config: mockConfig, }) - 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: '', + table: 'users', + column: 'user_id', + value: 'context.id()', + value_type: 'string', + operator: '=', + }, + ]) const sql = "DELETE FROM users WHERE name = 'Alice'" const modifiedSql = await applyRLS({ sql, @@ -106,10 +127,22 @@ describe('applyRLS - Query Modification', () => { config: mockConfig, }) - expect(modifiedSql).toContain("WHERE `name` = 'Alice'") + expect(modifiedSql).toContain("`name` = 'Alice'") + expect(modifiedSql).toContain("`users`.`user_id` = 'user123'") }) it('should modify UPDATE queries with additional WHERE clause', async () => { + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([ + { + actions: 'UPDATE', + schema: '', + table: 'users', + column: 'user_id', + value: 'context.id()', + value_type: 'string', + operator: '=', + }, + ]) const sql = "UPDATE users SET name = 'Bob' WHERE age = 25" const modifiedSql = await applyRLS({ sql, @@ -118,10 +151,23 @@ 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("`users`.`user_id` = 'user123'") }) it('should modify INSERT queries to enforce column values', async () => { + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([ + { + actions: 'INSERT', + schema: '', + table: 'users', + column: 'user_id', + value: 'context.id()', + value_type: 'string', + operator: '=', + }, + ]) const sql = "INSERT INTO users (user_id, name) VALUES (1, 'Alice')" const modifiedSql = await applyRLS({ sql, @@ -130,11 +176,94 @@ describe('applyRLS - Query Modification', () => { config: mockConfig, }) - expect(modifiedSql).toContain("VALUES (1,'Alice')") + expect(modifiedSql).toContain("VALUES ('user123','Alice')") + }) + + it('should throw when action is not allowed on a restricted table', async () => { + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([ + { + actions: 'SELECT', + schema: '', + table: 'users', + column: 'user_id', + value: 'context.id()', + value_type: 'string', + operator: '=', + }, + ]) + await expect( + applyRLS({ + sql: "DELETE FROM users WHERE name = 'Alice'", + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + ).rejects.toThrow( + 'Unauthorized access: No matching rules for DELETE on restricted table users' + ) + }) + + it('should throw when SQL is empty and RLS is enabled', async () => { + await expect( + applyRLS({ + sql: '', + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + ).rejects.toThrow('No SQL query found in RLS plugin.') + }) + + it('should support numeric value_type and CTE / UNION / subquery / multi-statement queries', async () => { + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([ + { + actions: 'SELECT', + schema: '', + table: 'users', + column: 'tenant_id', + value: '42', + value_type: 'number', + operator: '=', + }, + ]) + + const cteSql = + 'WITH active_users AS (SELECT * FROM users) SELECT * FROM active_users' + const modifiedCte = await applyRLS({ + sql: cteSql, + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + expect(modifiedCte).toContain('`users`.`tenant_id` =') + + const unionSql = + 'SELECT id FROM users UNION SELECT id FROM users WHERE id > 1' + const modifiedUnion = await applyRLS({ + sql: unionSql, + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + expect(modifiedUnion).toContain('UNION') + expect(modifiedUnion).toContain('`users`.`tenant_id` =') + + const multiSql = 'SELECT * FROM users; SELECT * FROM users WHERE id = 2' + const modifiedMulti = await applyRLS({ + sql: multiSql, + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + expect(modifiedMulti).toContain(';') }) }) describe('applyRLS - Edge Cases', () => { + beforeEach(() => { + mockConfig.role = 'client' + }) + it('should not modify SQL if RLS is disabled', async () => { const sql = 'SELECT * FROM users' const modifiedSql = await applyRLS({ @@ -148,26 +277,56 @@ describe('applyRLS - Edge Cases', () => { }) it('should not modify SQL if user is admin', async () => { - mockConfig.role = 'admin' + const adminConfig: StarbaseDBConfiguration = { + ...mockConfig, + role: 'admin', + } const sql = 'SELECT * FROM users' const modifiedSql = await applyRLS({ sql, isEnabled: true, dataSource: mockDataSource, - config: mockConfig, + config: adminConfig, }) expect(modifiedSql).toBe(sql) }) + + it('should return empty policies when executeQuery returns empty array', async () => { + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([]) + const res = await loadPolicies(mockDataSource) + expect(res).toEqual([]) + consoleErrorSpy.mockRestore() + }) + + it('should throw when SQL cannot be parsed', async () => { + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([]) + await expect( + applyRLS({ + sql: 'SELECT FROM WHERE ???', + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + ).rejects.toThrow() + consoleErrorSpy.mockRestore() + }) }) describe('applyRLS - Multi-Table Queries', () => { beforeEach(() => { + mockConfig.role = 'client' vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([ { actions: 'SELECT', - schema: 'public', + schema: '', table: 'users', column: 'user_id', value: 'context.id()', @@ -176,7 +335,7 @@ describe('applyRLS - Multi-Table Queries', () => { }, { actions: 'SELECT', - schema: 'public', + schema: '', table: 'orders', column: 'user_id', value: 'context.id()', @@ -200,8 +359,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 +377,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 subqueries inside FROM clause', async () => { @@ -236,6 +395,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..debb702 100644 --- a/src/rls/index.ts +++ b/src/rls/index.ts @@ -208,7 +208,9 @@ function applyRLSToAst(ast: any): void { // Handle WITH (CTE) queries as arrays if (ast.with && Array.isArray(ast.with)) { for (const cte of ast.with) { - if (cte.stmt) { + if (cte.stmt?.ast) { + applyRLSToAst(cte.stmt.ast) + } else if (cte.stmt) { applyRLSToAst(cte.stmt) } } @@ -264,13 +266,17 @@ 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] - } - return tableName - }) || [] + ast.from + ?.filter( + (fromTable: any) => typeof fromTable?.table === 'string' + ) + .map((fromTable: any) => { + let tableName = normalizeIdentifier(fromTable.table) + if (tableName.includes('.')) { + tableName = tableName.split('.')[1] + } + return tableName + }) || [] } const restrictedTables = Object.keys(tablesWithRules) @@ -349,7 +355,9 @@ function applyRLSToAst(ast: any): void { }) ast.from?.forEach((fromItem: any) => { - if (fromItem.expr && fromItem.expr.type === 'select') { + if (fromItem.expr?.ast && fromItem.expr.ast.type === 'select') { + applyRLSToAst(fromItem.expr.ast) + } else if (fromItem.expr && fromItem.expr.type === 'select') { applyRLSToAst(fromItem.expr) } @@ -359,7 +367,9 @@ function applyRLSToAst(ast: any): void { ? fromItem.join : [fromItem] joins.forEach((joinItem: any) => { - if (joinItem.expr && joinItem.expr.type === 'select') { + if (joinItem.expr?.ast && joinItem.expr.ast.type === 'select') { + applyRLSToAst(joinItem.expr.ast) + } else if (joinItem.expr && joinItem.expr.type === 'select') { applyRLSToAst(joinItem.expr) } })