diff --git a/src/allowlist/index.test.ts b/src/allowlist/index.test.ts new file mode 100644 index 0000000..df87f5f --- /dev/null +++ b/src/allowlist/index.test.ts @@ -0,0 +1,135 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { isQueryAllowed } from './index' +import type { DataSource } from '../types' +import type { StarbaseDBConfiguration } from '../handler' + +describe('Allowlist Module (isQueryAllowed)', () => { + let mockDataSource: DataSource + let mockConfig: StarbaseDBConfiguration + + beforeEach(() => { + vi.clearAllMocks() + mockDataSource = { + source: 'internal', + rpc: { + executeQuery: vi.fn(), + }, + } as any + mockConfig = { + role: 'client', + features: { allowlist: true }, + } + }) + + it('should allow any query when allowlist feature is disabled', async () => { + const result = await isQueryAllowed({ + sql: 'SELECT * FROM users', + isEnabled: false, + dataSource: mockDataSource, + config: mockConfig, + }) + expect(result).toBe(true) + expect(mockDataSource.rpc.executeQuery).not.toHaveBeenCalled() + }) + + it('should allow any query when user role is admin', async () => { + mockConfig.role = 'admin' + const result = await isQueryAllowed({ + sql: 'DROP TABLE users', + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + expect(result).toBe(true) + expect(mockDataSource.rpc.executeQuery).not.toHaveBeenCalled() + }) + + it('should return an Error when SQL is empty', async () => { + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([]) + const result = await isQueryAllowed({ + sql: '', + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + expect(result).toBeInstanceOf(Error) + expect((result as Error).message).toBe( + 'No SQL provided for allowlist check' + ) + }) + + it('should allow query matching an allowlisted SQL statement (ignoring trailing semicolon)', async () => { + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([ + { sql_statement: 'SELECT * FROM users', source: 'internal' }, + { sql_statement: 'SELECT * FROM other', source: 'external' }, + ]) + + const result = await isQueryAllowed({ + sql: 'SELECT * FROM users;', + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + expect(result).toBe(true) + }) + + it('should reject query not in allowlist and log rejection', async () => { + vi.mocked(mockDataSource.rpc.executeQuery) + .mockResolvedValueOnce([ + { + sql_statement: 'SELECT id FROM users WHERE active = 1', + source: 'internal', + }, + ]) + .mockResolvedValueOnce([]) + + await expect( + isQueryAllowed({ + sql: 'SELECT * FROM users WHERE id = 1', + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + ).rejects.toThrow('Query not allowed') + + expect(mockDataSource.rpc.executeQuery).toHaveBeenCalledTimes(2) + }) + + it('should reject when allowlist has different AST structure or array lengths', async () => { + vi.mocked(mockDataSource.rpc.executeQuery) + .mockResolvedValueOnce([ + { + sql_statement: 'SELECT id, name FROM users', + source: 'internal', + }, + ]) + .mockRejectedValueOnce(new Error('Rejection insert failed')) + + vi.spyOn(console, 'error').mockImplementation(() => {}) + + await expect( + isQueryAllowed({ + sql: 'SELECT id FROM users', + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + ).rejects.toThrow('Query not allowed') + }) + + it('should handle loadAllowlist DB errors gracefully and reject query', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.mocked(mockDataSource.rpc.executeQuery).mockRejectedValue( + new Error('DB connection error') + ) + + await expect( + isQueryAllowed({ + sql: 'SELECT * FROM users', + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + ).rejects.toThrow('Query not allowed') + }) +}) diff --git a/src/handler.test.ts b/src/handler.test.ts index 86bb328..897a9a2 100644 --- a/src/handler.test.ts +++ b/src/handler.test.ts @@ -199,4 +199,86 @@ describe('StarbaseDB Error Handling', () => { expect(response.status).toBe(500) }) + + it('should throw if 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 handle preAuth routes for authless plugins and return undefined otherwise', async () => { + const pluginInstance = new StarbaseDB({ + dataSource: mockDataSource, + config: mockConfig, + plugins: [ + { + opts: { requiresAuth: false }, + pathPrefix: '/public/:id/*', + } as any, + ], + }) + + const matched = await pluginInstance.handlePreAuth( + new Request('https://example.com/public/123/view'), + mockExecutionContext + ) + expect(matched).toBeDefined() + + const unmatched = await pluginInstance.handlePreAuth( + new Request('https://example.com/private/data'), + mockExecutionContext + ) + expect(unmatched).toBeUndefined() + }) + + it('should validate Content-Type, params, and transaction fields in queryRoute', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const badContentType = new Request('https://example.com/query', { + method: 'POST', + body: JSON.stringify({ sql: 'SELECT 1' }), + headers: { 'Content-Type': 'text/plain' }, + }) + expect((await instance.queryRoute(badContentType, false)).status).toBe( + 400 + ) + + const badParams = new Request('https://example.com/query', { + method: 'POST', + body: JSON.stringify({ sql: 'SELECT 1', params: 'invalid' }), + headers: { 'Content-Type': 'application/json' }, + }) + expect((await instance.queryRoute(badParams, false)).status).toBe(400) + + const badTxSql = new Request('https://example.com/query', { + method: 'POST', + body: JSON.stringify({ transaction: [{ sql: '' }] }), + headers: { 'Content-Type': 'application/json' }, + }) + expect((await instance.queryRoute(badTxSql, false)).status).toBe(500) + + const badTxParams = new Request('https://example.com/query', { + method: 'POST', + body: JSON.stringify({ + transaction: [{ sql: 'SELECT 1', params: 123 }], + }), + headers: { 'Content-Type': 'application/json' }, + }) + expect((await instance.queryRoute(badTxParams, false)).status).toBe(500) + }) + + it('should log error if expireCache fails', async () => { + const consoleSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + vi.mocked(mockDataSource.rpc.executeQuery).mockImplementationOnce(() => { + throw new Error('Cache cleanup failed') + }) + await instance['expireCache']() + expect(consoleSpy).toHaveBeenCalled() + }) }) diff --git a/src/import/csv.test.ts b/src/import/csv.test.ts new file mode 100644 index 0000000..d48b8cb --- /dev/null +++ b/src/import/csv.test.ts @@ -0,0 +1,163 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { importTableFromCsvRoute } from './csv' +import { executeOperation } from '../export' +import type { DataSource } from '../types' +import type { StarbaseDBConfiguration } from '../handler' + +vi.mock('../export', () => ({ + executeOperation: vi.fn(), +})) + +describe('CSV Import Module (importTableFromCsvRoute)', () => { + let mockDataSource: DataSource + let mockConfig: StarbaseDBConfiguration + + beforeEach(() => { + vi.clearAllMocks() + mockDataSource = { + source: 'internal', + rpc: { executeQuery: vi.fn() }, + } as any + mockConfig = { role: 'admin' } + }) + + it('should return 400 if request body is empty', async () => { + const req = new Request('http://localhost/import/csv/users', { + method: 'POST', + }) + const res = await importTableFromCsvRoute( + 'users', + req, + mockDataSource, + mockConfig + ) + expect(res.status).toBe(400) + }) + + it('should return 400 for unsupported Content-Type', async () => { + const req = new Request('http://localhost/import/csv/users', { + method: 'POST', + body: 'id,name\n1,Alice', + headers: { 'Content-Type': 'text/plain' }, + }) + const res = await importTableFromCsvRoute( + 'users', + req, + mockDataSource, + mockConfig + ) + expect(res.status).toBe(400) + }) + + it('should import CSV from application/json with columnMapping', async () => { + vi.mocked(executeOperation).mockResolvedValue({ status: 200 }) + const req = new Request('http://localhost/import/csv/users', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + data: 'full_name,user_age\nAlice,30\nBob,25', + columnMapping: { full_name: 'name', user_age: 'age' }, + }), + }) + const res = await importTableFromCsvRoute( + 'users', + req, + mockDataSource, + mockConfig + ) + expect(res.status).toBe(200) + expect(executeOperation).toHaveBeenCalledTimes(2) + const json = (await res.json()) as { + result: { message: string; failedStatements: any[] } + } + expect(json.result.message).toContain('Imported 2 out of 2 records') + expect(json.result.failedStatements).toEqual([]) + }) + + it('should import raw text/csv and record failed statements', async () => { + vi.mocked(executeOperation) + .mockResolvedValueOnce({ status: 200 }) + .mockRejectedValueOnce(new Error('Constraint violation')) + + const req = new Request('http://localhost/import/csv/users', { + method: 'POST', + headers: { 'Content-Type': 'text/csv' }, + body: 'id,name\n1,Alice\n2,Bob', + }) + const res = await importTableFromCsvRoute( + 'users', + req, + mockDataSource, + mockConfig + ) + expect(res.status).toBe(200) + const json = (await res.json()) as { + result: { message: string; failedStatements: any[] } + } + expect(json.result.message).toContain('Imported 1 out of 2 records') + expect(json.result.failedStatements).toHaveLength(1) + }) + + it('should import CSV from multipart/form-data and reject missing file', async () => { + vi.mocked(executeOperation).mockResolvedValue({ status: 200 }) + + const emptyForm = new FormData() + const missingReq = new Request('http://localhost/import/csv/users', { + method: 'POST', + body: emptyForm, + }) + const missingRes = await importTableFromCsvRoute( + 'users', + missingReq, + mockDataSource, + mockConfig + ) + expect(missingRes.status).toBe(400) + + const form = new FormData() + const file = new File(['id,name\n1,Alice'], 'users.csv', { + type: 'text/csv', + }) + form.append('file', file) + const okReq = new Request('http://localhost/import/csv/users', { + method: 'POST', + body: form, + }) + const okRes = await importTableFromCsvRoute( + 'users', + okReq, + mockDataSource, + mockConfig + ) + expect(okRes.status).toBe(200) + }) + + it('should return 400 when CSV has no valid records and 500 on parse exception', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const emptyCsvReq = new Request('http://localhost/import/csv/users', { + method: 'POST', + headers: { 'Content-Type': 'text/csv' }, + body: 'id,name', + }) + const emptyRes = await importTableFromCsvRoute( + 'users', + emptyCsvReq, + mockDataSource, + mockConfig + ) + expect(emptyRes.status).toBe(400) + + const badJsonReq = new Request('http://localhost/import/csv/users', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: 'not-json', + }) + const errRes = await importTableFromCsvRoute( + 'users', + badJsonReq, + mockDataSource, + mockConfig + ) + expect(errRes.status).toBe(500) + }) +}) diff --git a/src/index.test.ts b/src/index.test.ts new file mode 100644 index 0000000..8585c80 --- /dev/null +++ b/src/index.test.ts @@ -0,0 +1,227 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import worker, { Env } from './index' +import { jwtVerify } from 'jose' + +vi.mock('./do', () => ({ + StarbaseDBDurableObject: vi.fn(), +})) + +const mockHandlePreAuth = vi.fn() +const mockHandle = vi.fn() + +vi.mock('./handler', () => ({ + StarbaseDB: vi.fn().mockImplementation((opts) => ({ + opts, + handlePreAuth: mockHandlePreAuth, + handle: mockHandle, + })), +})) + +vi.mock('jose', () => ({ + createRemoteJWKSet: vi.fn(() => 'mock-jwks'), + jwtVerify: vi.fn(), +})) + +vi.mock('../plugins/websocket', () => ({ + WebSocketPlugin: vi.fn(() => ({ opts: {}, pathPrefix: '/ws' })), +})) +vi.mock('../plugins/studio', () => ({ + StudioPlugin: vi.fn(() => ({ opts: {}, pathPrefix: '/studio' })), +})) +vi.mock('../plugins/sql-macros', () => ({ + SqlMacrosPlugin: vi.fn(() => ({ opts: {} })), +})) +vi.mock('../plugins/cdc', () => ({ + ChangeDataCapturePlugin: vi.fn(() => ({ + opts: {}, + onEvent: vi.fn(), + })), +})) +vi.mock('../plugins/query-log', () => ({ + QueryLogPlugin: vi.fn(() => ({ opts: {} })), +})) +vi.mock('../plugins/stats', () => ({ + StatsPlugin: vi.fn(() => ({ opts: {} })), +})) +vi.mock('../plugins/cron', () => ({ + CronPlugin: vi.fn(() => ({ + opts: {}, + onEvent: vi.fn(), + })), +})) +vi.mock('../plugins/interface', () => ({ + InterfacePlugin: vi.fn(() => ({ + opts: {}, + matchesRoute: vi.fn((path: string) => path === '/ui'), + })), +})) + +describe('Worker Entrypoint & Router (src/index.ts)', () => { + let env: Env + let ctx: ExecutionContext + let mockStub: any + + beforeEach(() => { + vi.clearAllMocks() + mockHandlePreAuth.mockResolvedValue(undefined) + mockHandle.mockResolvedValue( + new Response(JSON.stringify({ ok: true }), { status: 200 }) + ) + + mockStub = { + init: vi.fn().mockResolvedValue({ executeQuery: vi.fn() }), + } + + env = { + ADMIN_AUTHORIZATION_TOKEN: 'admin-secret', + CLIENT_AUTHORIZATION_TOKEN: 'client-secret', + REGION: 'auto', + DATABASE_DURABLE_OBJECT: { + idFromName: vi.fn(() => 'do-id' as any), + get: vi.fn(() => mockStub), + } as any, + HYPERDRIVE: {} as any, + } + + ctx = { + waitUntil: vi.fn(), + passThroughOnException: vi.fn(), + } as any + }) + + it('should handle CORS preflight OPTIONS requests', async () => { + const req = new Request('http://localhost/query', { method: 'OPTIONS' }) + const res = await worker.fetch(req, env, ctx) + expect(res.status).toBe(204) + }) + + it('should return 401 when no Authorization token is provided', async () => { + const req = new Request('http://localhost/query', { method: 'POST' }) + const res = await worker.fetch(req, env, ctx) + expect(res.status).toBe(401) + }) + + it('should authenticate admin token and forward to StarbaseDB.handle', async () => { + const req = new Request('http://localhost/query', { + method: 'POST', + headers: { Authorization: 'Bearer admin-secret' }, + }) + const res = await worker.fetch(req, env, ctx) + expect(res.status).toBe(200) + expect(mockHandle).toHaveBeenCalledTimes(1) + }) + + it('should authenticate client token and handle locationHint region', async () => { + env.REGION = 'wnam' + const req = new Request('http://localhost/query?source=external', { + method: 'POST', + headers: { Authorization: 'Bearer client-secret' }, + }) + const res = await worker.fetch(req, env, ctx) + expect(res.status).toBe(200) + expect(env.DATABASE_DURABLE_OBJECT.get).toHaveBeenCalledWith('do-id', { + locationHint: 'wnam', + }) + }) + + it('should authenticate WebSocket requests via query token', async () => { + const req = new Request( + 'http://localhost/ws?token=client-secret&source=hyperdrive', + { + headers: { Upgrade: 'websocket' }, + } + ) + const res = await worker.fetch(req, env, ctx) + expect(res.status).toBe(200) + }) + + it('should reject invalid token when AUTH_JWKS_ENDPOINT is not configured', async () => { + const req = new Request('http://localhost/query', { + method: 'POST', + headers: { Authorization: 'Bearer wrong-token' }, + }) + const res = await worker.fetch(req, env, ctx) + expect(res.status).toBe(400) + const body = (await res.json()) as { error: string } + expect(body.error).toBe('Unauthorized request') + }) + + it('should verify JWT via JWKS endpoint and reject missing sub', async () => { + env.AUTH_JWKS_ENDPOINT = 'https://example.com/.well-known/jwks.json' + env.AUTH_ALGORITHM = 'RS256' + + vi.mocked(jwtVerify).mockResolvedValueOnce({ + payload: { sub: 'user-123' }, + } as any) + const okReq = new Request('http://localhost/query', { + headers: { Authorization: 'Bearer valid-jwt' }, + }) + expect((await worker.fetch(okReq, env, ctx)).status).toBe(200) + + vi.mocked(jwtVerify).mockResolvedValueOnce({ + payload: {}, + } as any) + const noSubReq = new Request('http://localhost/query', { + headers: { Authorization: 'Bearer no-sub-jwt' }, + }) + const noSubRes = await worker.fetch(noSubReq, env, ctx) + expect(noSubRes.status).toBe(400) + }) + + it('should return early for preAuthRequest and InterfacePlugin routes', async () => { + mockHandlePreAuth.mockResolvedValueOnce( + new Response('pre-auth', { status: 200 }) + ) + const preAuthReq = new Request('http://localhost/studio') + const preAuthRes = await worker.fetch(preAuthReq, env, ctx) + expect(await preAuthRes.text()).toBe('pre-auth') + + const uiReq = new Request('http://localhost/ui') + const uiRes = await worker.fetch(uiReq, env, ctx) + expect(uiRes.status).toBe(200) + }) + + it('should configure external DB sources (postgresql, mysql, sqlite providers, hyperdrive)', async () => { + const configs: Partial[] = [ + { EXTERNAL_DB_TYPE: 'postgresql', EXTERNAL_DB_HOST: 'localhost' }, + { EXTERNAL_DB_TYPE: 'mysql', EXTERNAL_DB_HOST: 'localhost' }, + { + EXTERNAL_DB_TYPE: 'sqlite', + EXTERNAL_DB_CLOUDFLARE_API_KEY: 'd1-key', + }, + { + EXTERNAL_DB_TYPE: 'sqlite', + EXTERNAL_DB_STARBASEDB_URI: 'sb-uri', + }, + { + EXTERNAL_DB_TYPE: 'sqlite', + EXTERNAL_DB_TURSO_URI: 'libsql://turso', + }, + { + HYPERDRIVE: { connectionString: 'postgres://hd' } as any, + }, + ] + + for (const extra of configs) { + const req = new Request('http://localhost/query', { + headers: { + Authorization: 'Bearer admin-secret', + 'X-Starbase-Source': 'external', + }, + }) + const res = await worker.fetch(req, { ...env, ...extra }, ctx) + expect(res.status).toBe(200) + } + }) + + it('should return 400 if an unexpected error occurs in fetch', async () => { + mockStub.init.mockRejectedValueOnce(new Error('DO init failed')) + const req = new Request('http://localhost/query', { + headers: { Authorization: 'Bearer admin-secret' }, + }) + const res = await worker.fetch(req, env, ctx) + expect(res.status).toBe(400) + const body = (await res.json()) as { error: string } + expect(body.error).toBe('DO init failed') + }) +}) diff --git a/src/literest/index.test.ts b/src/literest/index.test.ts index 51f8b31..f889250 100644 --- a/src/literest/index.test.ts +++ b/src/literest/index.test.ts @@ -488,5 +488,275 @@ describe('LiteREST', () => { expect(query).not.toContain('DROP TABLE users') }) + + it('should handle IN operator and multiple filter operators', async () => { + vi.mocked(executeQuery).mockResolvedValue([{ name: 'id', pk: 1 }]) + const searchParams = new URLSearchParams({ + 'status.in': 'active,pending', + 'age.gte': '18', + 'name.like': '%Ali%', + }) + + // @ts-expect-error: Testing private method + const { query, params } = await liteRest.buildSelectQuery( + 'users', + 'main', + undefined, + searchParams + ) + + expect(query).toContain('status IN (?, ?)') + expect(query).toContain('age >= ?') + expect(query).toContain('name LIKE ?') + expect(params).toEqual(['active', 'pending', '18', '%Ali%']) + }) + }) + + describe('Edge cases, fake/missing tables, -1, null, and CRUD endpoints', () => { + it('should throw error when table name is missing in path', async () => { + const request = new Request('http://localhost/rest/', { + method: 'GET', + }) + await expect(liteRest.handleRequest(request)).rejects.toThrow( + 'Expected a table name in the path' + ) + }) + + it('should handle single-segment table path without schema', async () => { + vi.mocked(executeQuery).mockResolvedValue([{ name: 'id', pk: 1 }]) + vi.mocked(executeTransaction).mockResolvedValue([ + [{ id: 1, name: 'Alice' }], + ]) + + const request = new Request('http://localhost/rest/users', { + method: 'GET', + }) + const response = await liteRest.handleRequest(request) + expect(response.status).toBe(200) + }) + + it('should return 500 when querying a fake/non-existent table', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.mocked(executeQuery).mockRejectedValue( + new Error('no such table: fake_table') + ) + + const request = new Request('http://localhost/rest/main/fake_table', { + method: 'GET', + }) + const response = await liteRest.handleRequest(request) + expect(response.status).toBe(500) + const body = (await response.json()) as { error: string } + expect(body.error).toContain('no such table: fake_table') + }) + + it('should handle GET with id -1 and id null safely', async () => { + vi.mocked(executeQuery).mockResolvedValue([{ name: 'id', pk: 1 }]) + vi.mocked(executeTransaction).mockResolvedValue([[]]) + + const reqNeg = new Request('http://localhost/rest/main/users/-1', { + method: 'GET', + }) + const resNeg = await liteRest.handleRequest(reqNeg) + expect(resNeg.status).toBe(200) + + const reqNull = new Request( + 'http://localhost/rest/main/users/null', + { method: 'GET' } + ) + const resNull = await liteRest.handleRequest(reqNull) + expect(resNull.status).toBe(200) + }) + + it('should wrap non-array GET result in an array', async () => { + vi.mocked(executeQuery).mockResolvedValue([{ name: 'id', pk: 1 }]) + vi.mocked(executeTransaction).mockResolvedValue([ + { id: 1, name: 'Single' }, + ]) + + const request = new Request('http://localhost/rest/main/users/1', { + method: 'GET', + }) + const response = await liteRest.handleRequest(request) + expect(response.status).toBe(200) + const json = (await response.json()) as { result: any } + expect(json.result).toEqual([{ id: 1, name: 'Single' }]) + }) + + it('should handle POST empty object and non-Error rejection', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const emptyReq = new Request('http://localhost/rest/main/users', { + method: 'POST', + body: JSON.stringify({}), + }) + const emptyRes = await liteRest.handleRequest(emptyReq) + expect(emptyRes.status).toBe(400) + + vi.mocked(executeTransaction).mockRejectedValue({ + error: 'Constraint failed', + }) + const errReq = new Request('http://localhost/rest/main/users', { + method: 'POST', + body: JSON.stringify({ name: 'Bob' }), + }) + const errRes = await liteRest.handleRequest(errReq) + expect(errRes.status).toBe(500) + }) + + it('should handle PATCH validation errors and success', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.mocked(executeQuery).mockResolvedValue([{ name: 'id', pk: 1 }]) + + const noPkReq = new Request('http://localhost/rest/main/users', { + method: 'PATCH', + body: JSON.stringify({ name: 'Updated' }), + }) + expect((await liteRest.handleRequest(noPkReq)).status).toBe(400) + + const onlyPkReq = new Request( + 'http://localhost/rest/main/users/1', + { + method: 'PATCH', + body: JSON.stringify({ id: 1 }), + } + ) + expect((await liteRest.handleRequest(onlyPkReq)).status).toBe(400) + + vi.mocked(executeTransaction).mockResolvedValue([{}]) + const okReq = new Request('http://localhost/rest/main/users/1', { + method: 'PATCH', + body: JSON.stringify({ name: 'Updated' }), + }) + expect((await liteRest.handleRequest(okReq)).status).toBe(200) + }) + + it('should handle PUT validation errors, DB error, and success', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.mocked(executeQuery).mockResolvedValue([{ name: 'id', pk: 1 }]) + + const noPkReq = new Request('http://localhost/rest/main/users', { + method: 'PUT', + body: JSON.stringify({ name: 'PutUser' }), + }) + expect((await liteRest.handleRequest(noPkReq)).status).toBe(400) + + const invalidReq = new Request( + 'http://localhost/rest/main/users/1', + { + method: 'PUT', + body: JSON.stringify(null), + } + ) + expect((await liteRest.handleRequest(invalidReq)).status).toBe(400) + + const emptyReq = new Request('http://localhost/rest/main/users/1', { + method: 'PUT', + body: JSON.stringify({}), + }) + expect((await liteRest.handleRequest(emptyReq)).status).toBe(400) + + vi.mocked(executeTransaction).mockResolvedValue([{}]) + const okReq = new Request('http://localhost/rest/main/users/1', { + method: 'PUT', + body: JSON.stringify({ name: 'PutUser' }), + }) + expect((await liteRest.handleRequest(okReq)).status).toBe(200) + + vi.mocked(executeTransaction).mockRejectedValue( + new Error('PUT failed') + ) + const errReq = new Request('http://localhost/rest/main/users/1', { + method: 'PUT', + body: JSON.stringify({ name: 'PutUser' }), + }) + expect((await liteRest.handleRequest(errReq)).status).toBe(500) + }) + + it('should handle DELETE missing id, missing PK, DB error, and success', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.mocked(executeQuery).mockResolvedValue([{ name: 'id', pk: 1 }]) + + const noIdReq = new Request('http://localhost/rest/main/users', { + method: 'DELETE', + }) + expect((await liteRest.handleRequest(noIdReq)).status).toBe(400) + + vi.mocked(executeQuery).mockResolvedValue([]) + const noPkTableReq = new Request( + 'http://localhost/rest/main/users/1', + { method: 'DELETE' } + ) + expect((await liteRest.handleRequest(noPkTableReq)).status).toBe( + 400 + ) + + vi.mocked(executeQuery).mockResolvedValue([{ name: 'id', pk: 1 }]) + vi.mocked(executeTransaction).mockResolvedValue([{}]) + const okReq = new Request('http://localhost/rest/main/users/1', { + method: 'DELETE', + }) + expect((await liteRest.handleRequest(okReq)).status).toBe(200) + + vi.mocked(executeTransaction).mockRejectedValue( + new Error('DELETE failed') + ) + const errReq = new Request('http://localhost/rest/main/users/1', { + method: 'DELETE', + }) + expect((await liteRest.handleRequest(errReq)).status).toBe(500) + }) + + it('should retrieve primary keys for postgresql, mysql, and composite keys', async () => { + const pgLiteRest = new LiteREST( + { + source: 'external', + external: { dialect: 'postgresql' }, + rpc: { executeQuery: vi.fn() }, + } as any, + mockConfig + ) + vi.mocked(executeQuery).mockResolvedValue([ + { name: 'tenant_id' }, + { name: 'user_id' }, + ]) + // @ts-expect-error: Testing private method + const pgPks = await pgLiteRest.getPrimaryKeyColumns('users') + expect(pgPks).toEqual(['tenant_id', 'user_id']) + + const mysqlLiteRest = new LiteREST( + { + source: 'external', + external: { dialect: 'mysql' }, + rpc: { executeQuery: vi.fn() }, + } as any, + mockConfig + ) + vi.mocked(executeQuery).mockResolvedValue([{ name: 'id' }]) + // @ts-expect-error: Testing private method + const mysqlPks = await mysqlLiteRest.getPrimaryKeyColumns('users') + expect(mysqlPks).toEqual(['id']) + + // @ts-expect-error: Testing private method + const compositeMissing = pgLiteRest.getPrimaryKeyConditions( + ['tenant_id', 'user_id'], + undefined, + { tenant_id: 't1' }, + new URLSearchParams() + ) + expect(compositeMissing.error).toContain('user_id') + + // @ts-expect-error: Testing private method + const compositeOk = pgLiteRest.getPrimaryKeyConditions( + ['tenant_id', 'user_id'], + undefined, + { tenant_id: 't1', user_id: 'u1' }, + new URLSearchParams() + ) + expect(compositeOk.conditions).toEqual([ + 'tenant_id = ?', + 'user_id = ?', + ]) + expect(compositeOk.params).toEqual(['t1', 'u1']) + }) }) }) diff --git a/src/operation.test.ts b/src/operation.test.ts index f52cbb9..1cca646 100644 --- a/src/operation.test.ts +++ b/src/operation.test.ts @@ -87,6 +87,44 @@ import type { SqlConnection } from '@outerbase/sdk/dist/connections/sql-base' // } // }) +vi.mock('pg', () => ({ + Client: vi.fn(() => ({})), +})) +vi.mock('mysql2', () => ({ + createConnection: vi.fn(() => ({})), +})) +vi.mock('@libsql/client/web', () => ({ + createClient: vi.fn(() => ({})), +})) +vi.mock('postgres', () => ({ + default: vi.fn(() => { + const sqlFn: any = { + unsafe: vi.fn().mockResolvedValue([{ id: 1, name: 'HD' }]), + end: vi.fn().mockResolvedValue(undefined), + } + return sqlFn + }), +})) + +const mockConnect = vi.fn().mockResolvedValue(undefined) +const mockRaw = vi + .fn() + .mockResolvedValue({ data: [{ id: 1, name: 'SDK-Result' }] }) + +vi.mock('@outerbase/sdk', () => { + const makeConn = () => ({ + connect: mockConnect, + raw: mockRaw, + }) + return { + PostgreSQLConnection: vi.fn(makeConn), + MySQLConnection: vi.fn(makeConn), + TursoConnection: vi.fn(makeConn), + CloudflareD1Connection: vi.fn(makeConn), + StarbaseConnection: vi.fn(makeConn), + } +}) + vi.mock('./allowlist', () => ({ isQueryAllowed: vi.fn() })) vi.mock('./rls', () => ({ applyRLS: vi.fn(async ({ sql }) => sql) })) vi.mock('./cache', () => ({ @@ -585,3 +623,189 @@ describe('executeExternalQuery', () => { // ).rejects.toThrow('Query execution failed') // }) // }) + +describe('executeQuery - Raw, Registry, Hyperdrive, and External', () => { + it('should transform raw results and invoke registry hooks', async () => { + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue({ + columns: ['id', 'name'], + rows: [[1, 'Alice']], + } as any) + + mockDataSource.registry = { + beforeQuery: vi.fn(async ({ sql, params }) => ({ sql, params })), + afterQuery: vi.fn(async ({ result }) => result), + } as any + + const result = await executeQuery({ + sql: 'SELECT * FROM users', + params: undefined, + isRaw: true, + dataSource: mockDataSource, + config: mockConfig, + }) + + expect(mockDataSource.registry!.beforeQuery).toHaveBeenCalledTimes(1) + expect(mockDataSource.registry!.afterQuery).toHaveBeenCalledTimes(1) + expect(result).toEqual({ + columns: ['id', 'name'], + rows: [[1, 'Alice']], + meta: { rows_read: 1, rows_written: 0 }, + }) + }) + + it('should handle registry.afterQuery error gracefully and return empty array if rpc returns null', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValueOnce( + null as any + ) + const emptyRes = await executeQuery({ + sql: 'SELECT * FROM users', + params: undefined, + isRaw: false, + dataSource: mockDataSource, + config: mockConfig, + }) + expect(emptyRes).toEqual([]) + + vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValueOnce([ + { id: 1 }, + ]) + mockDataSource.registry = { + beforeQuery: vi.fn(async ({ sql, params }) => ({ sql, params })), + afterQuery: vi.fn().mockRejectedValue(new Error('Hook failed')), + } as any + + const res = await executeQuery({ + sql: 'SELECT * FROM users', + params: undefined, + isRaw: false, + dataSource: mockDataSource, + config: mockConfig, + }) + expect(res).toEqual([{ id: 1 }]) + }) + + it('should execute hyperdrive queries with and without executionContext', async () => { + const hdSource: any = { + source: 'hyperdrive', + external: { connectionString: 'postgres://localhost/db' }, + executionContext: { waitUntil: vi.fn() }, + } + const res1 = await executeQuery({ + sql: 'SELECT 1', + params: [], + isRaw: false, + dataSource: hdSource, + config: mockConfig, + }) + expect(res1).toEqual([{ id: 1, name: 'HD' }]) + expect(hdSource.executionContext.waitUntil).toHaveBeenCalled() + + delete hdSource.executionContext + const res2 = await executeQuery({ + sql: 'SELECT 1', + params: [], + isRaw: false, + dataSource: hdSource, + config: mockConfig, + }) + expect(res2).toEqual([{ id: 1, name: 'HD' }]) + }) + + it('should throw error if hyperdrive connectionString is missing', async () => { + const hdSource: any = { source: 'hyperdrive', external: {} } + await expect( + executeQuery({ + sql: 'SELECT 1', + params: [], + isRaw: false, + dataSource: hdSource, + config: mockConfig, + }) + ).rejects.toThrow('Hyperdrive connection string not found') + }) + + it('should return empty array in executeTransaction when dataSource is missing', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const res = await executeTransaction({ + queries: [{ sql: 'SELECT 1' }], + isRaw: false, + dataSource: null as any, + config: mockConfig, + }) + expect(res).toEqual([]) + }) +}) + +describe('executeExternalQuery & executeSDKQuery', () => { + it('should convert array params and handle malformed API response', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ + json: async () => ({ response: {} }), + } as any) + + const res = await executeExternalQuery({ + sql: 'SELECT * FROM users WHERE id = ?', + params: [42], + dataSource: mockDataSource, + config: mockConfig, + }) + expect(res).toEqual([]) + expect(fetchMock).toHaveBeenCalled() + fetchMock.mockRestore() + }) + + it('should forward to executeSDKQuery when outerbaseApiKey is not set', async () => { + mockConfig.outerbaseApiKey = undefined + const res = await executeExternalQuery({ + sql: 'SELECT * FROM users', + params: [], + dataSource: mockDataSource, + config: mockConfig, + }) + expect(res).toEqual([{ id: 1, name: 'SDK-Result' }]) + }) + + it('should return empty array when external is missing in executeSDKQuery', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + mockDataSource.external = undefined + const res = await executeSDKQuery({ + sql: 'SELECT 1', + params: [], + dataSource: mockDataSource, + config: mockConfig, + }) + expect(res).toEqual([]) + }) + + it('should execute SDK queries for postgresql, mysql, cloudflare-d1, starbase, turso, and throw on unsupported', async () => { + const providers: 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: 'd' }, + { dialect: 'sqlite', provider: 'starbase', apiKey: 'k', token: 't' }, + { dialect: 'sqlite', provider: 'turso', uri: 'u', token: 't' }, + ] + + for (const ext of providers) { + mockDataSource.external = ext + const res = await executeSDKQuery({ + sql: 'SELECT 1', + params: [], + dataSource: mockDataSource, + config: mockConfig, + }) + expect(res).toEqual([{ id: 1, name: 'SDK-Result' }]) + } + + mockDataSource.external = { dialect: 'oracle' } as any + await expect( + executeSDKQuery({ + sql: 'SELECT 1', + params: [], + dataSource: mockDataSource, + config: mockConfig, + }) + ).rejects.toThrow('Unsupported external database type') + }) +}) diff --git a/src/rls/index.test.ts b/src/rls/index.test.ts index cf00156..b3bc369 100644 --- a/src/rls/index.test.ts +++ b/src/rls/index.test.ts @@ -71,11 +71,12 @@ describe('loadPolicies - Policy Fetching and Parsing', () => { describe('applyRLS - Query Modification', () => { beforeEach(() => { vi.resetAllMocks() + mockConfig.role = 'client' mockDataSource.context.sub = 'user123' vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([ { - actions: 'SELECT', - schema: 'public', + actions: '*', + schema: '', table: 'users', column: 'user_id', value: 'context.id()', @@ -86,6 +87,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 +106,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 +128,21 @@ describe('applyRLS - Query Modification', () => { config: mockConfig, }) - expect(modifiedSql).toContain("WHERE `name` = 'Alice'") + expect(modifiedSql).toContain("(`name` = 'Alice') AND (`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,22 @@ describe('applyRLS - Query Modification', () => { config: mockConfig, }) - expect(modifiedSql).toContain("`name` = 'Bob' WHERE `age` = 25") + expect(modifiedSql).toContain("`name` = 'Bob'") + expect(modifiedSql).toContain("(`age` = 25) AND (`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,7 +175,7 @@ describe('applyRLS - Query Modification', () => { config: mockConfig, }) - expect(modifiedSql).toContain("VALUES (1,'Alice')") + expect(modifiedSql).toContain("VALUES ('user123','Alice')") }) }) @@ -164,10 +209,12 @@ describe('applyRLS - Edge Cases', () => { describe('applyRLS - Multi-Table Queries', () => { beforeEach(() => { + mockConfig.role = 'client' + mockDataSource.context.sub = 'user123' vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([ { actions: 'SELECT', - schema: 'public', + schema: '', table: 'users', column: 'user_id', value: 'context.id()', @@ -176,7 +223,7 @@ describe('applyRLS - Multi-Table Queries', () => { }, { actions: 'SELECT', - schema: 'public', + schema: '', table: 'orders', column: 'user_id', value: 'context.id()', @@ -200,8 +247,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,24 +265,58 @@ 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 () => { + it('should throw when applying RLS to subqueries inside FROM clause without table name', async () => { const sql = ` SELECT * FROM ( SELECT * FROM users WHERE age > 18 ) AS adults ` + await expect( + applyRLS({ + sql, + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + ).rejects.toThrow() + }) + + it('should throw error for unauthorized action on restricted table', async () => { + await expect( + applyRLS({ + sql: "DELETE FROM users WHERE id = 1", + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + ).rejects.toThrow('Unauthorized access') + }) + + it('should throw error if sql is empty', async () => { + await expect( + applyRLS({ + sql: '', + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + ).rejects.toThrow('No SQL query found in RLS plugin.') + }) + + it('should handle multiple statements', async () => { + const sql = 'SELECT * FROM users; SELECT * FROM orders' const modifiedSql = await applyRLS({ sql, isEnabled: true, dataSource: mockDataSource, config: mockConfig, }) - - expect(modifiedSql).toContain("WHERE `users.user_id` = 'user123'") + expect(modifiedSql).toContain("`users`.`user_id` = 'user123'") + expect(modifiedSql).toContain("`orders`.`user_id` = 'user123'") }) })