From 85164e323310d8c8bad7c6c714da32b6a0c234a3 Mon Sep 17 00:00:00 2001 From: Hidayat666-ali <186366795+Hidayat666-ali@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:31:33 +0530 Subject: [PATCH] test(vitest): expand test coverage across allowlist, sql-macros, and resend plugins (#71) Resolves #71 /claim #71 --- plugins/resend/index.test.ts | 79 +++++++++++++++ plugins/sql-macros/index.test.ts | 141 ++++++++++++++++++++++++++ src/allowlist/index.test.ts | 166 +++++++++++++++++++++++++++++++ src/allowlist/index.ts | 2 +- 4 files changed, 387 insertions(+), 1 deletion(-) create mode 100644 plugins/resend/index.test.ts create mode 100644 plugins/sql-macros/index.test.ts create mode 100644 src/allowlist/index.test.ts diff --git a/plugins/resend/index.test.ts b/plugins/resend/index.test.ts new file mode 100644 index 0000000..8faae21 --- /dev/null +++ b/plugins/resend/index.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest' +import { ResendPlugin } from './index' + +describe('ResendPlugin', () => { + beforeEach(() => { + vi.restoreAllMocks() + }) + + it('should initialize with correct plugin name and options', () => { + const plugin = new ResendPlugin({ apiKey: 're_test_key_123' }) + expect(plugin.name).toBe('starbasedb:resend') + expect(plugin.apiKey).toBe('re_test_key_123') + }) + + it('should initialize without options', () => { + const plugin = new ResendPlugin() + expect(plugin.name).toBe('starbasedb:resend') + expect(plugin.apiKey).toBeUndefined() + }) + + it('should send email successfully with proper payload and authorization header', async () => { + const plugin = new ResendPlugin({ apiKey: 're_valid_api_key' }) + const mockResponse = { id: 'email_12345' } + + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: async () => mockResponse, + }) + global.fetch = fetchMock + + const result = await plugin.sendEmail( + 'onboarding@resend.dev', + ['user@example.com'], + 'Welcome to Starbase', + '
Hello World
' + ) + + expect(result).toEqual(mockResponse) + expect(fetchMock).toHaveBeenCalledWith('https://api.resend.com/emails', { + method: 'POST', + headers: { + Authorization: 'Bearer re_valid_api_key', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + from: 'onboarding@resend.dev', + to: ['user@example.com'], + subject: 'Welcome to Starbase', + html: 'Hello World
', + }), + }) + }) + + it('should throw an error when API returns a non-ok response with a message', async () => { + const plugin = new ResendPlugin({ apiKey: 're_invalid_api_key' }) + + global.fetch = vi.fn().mockResolvedValue({ + ok: false, + json: async () => ({ message: 'Invalid API Key' }), + }) + + await expect( + plugin.sendEmail('test@test.com', ['dest@dest.com'], 'Test', 'Body') + ).rejects.toThrow('Invalid API Key') + }) + + it('should throw fallback error when API response lacks a message', async () => { + const plugin = new ResendPlugin({ apiKey: 're_key' }) + + global.fetch = vi.fn().mockResolvedValue({ + ok: false, + json: async () => ({}), + }) + + await expect( + plugin.sendEmail('test@test.com', ['dest@dest.com'], 'Test', 'Body') + ).rejects.toThrow('Failed to send email') + }) +}) diff --git a/plugins/sql-macros/index.test.ts b/plugins/sql-macros/index.test.ts new file mode 100644 index 0000000..433cf9c --- /dev/null +++ b/plugins/sql-macros/index.test.ts @@ -0,0 +1,141 @@ +import { describe, expect, it, vi } from 'vitest' +import { SqlMacrosPlugin } from './index' +import { DataSource } from '../../src/types' +import { StarbaseDBConfiguration } from '../../src/handler' + +describe('SqlMacrosPlugin', () => { + const mockInternalDataSource: DataSource = { + name: 'test-db', + source: 'internal', + type: 'sqlite', + rpc: { + executeQuery: vi.fn(), + } as any, + } + + const mockExternalDataSource: DataSource = { + name: 'pg-db', + source: 'external', + type: 'postgres', + rpc: { executeQuery: vi.fn() } as any, + } + + const userConfig: StarbaseDBConfiguration = { + role: 'user', + } as any + + const adminConfig: StarbaseDBConfiguration = { + role: 'admin', + } as any + + it('should initialize with correct plugin name and options', () => { + const plugin = new SqlMacrosPlugin({ preventSelectStar: true }) + expect(plugin.name).toBe('starbasedb:sql-macros') + expect(plugin.preventSelectStar).toBe(true) + }) + + it('should return original sql when no dataSource is provided', async () => { + const plugin = new SqlMacrosPlugin({ preventSelectStar: true }) + const res = await plugin.beforeQuery({ + sql: 'SELECT * FROM users', + params: [], + }) + expect(res.sql).toBe('SELECT * FROM users') + }) + + describe('preventSelectStar enforcement', () => { + it('should throw error when non-admin executes SELECT *', async () => { + const plugin = new SqlMacrosPlugin({ preventSelectStar: true }) + plugin.config = userConfig + + await expect( + plugin.beforeQuery({ + sql: 'SELECT * FROM users', + dataSource: mockInternalDataSource, + config: userConfig, + }) + ).rejects.toThrow('SELECT * is not allowed. Please specify explicit columns.') + }) + + it('should allow SELECT * when user has admin role', async () => { + const plugin = new SqlMacrosPlugin({ preventSelectStar: true }) + plugin.config = adminConfig + + const res = await plugin.beforeQuery({ + sql: 'SELECT * FROM users', + dataSource: mockInternalDataSource, + config: adminConfig, + }) + expect(res.sql).toBe('SELECT * FROM users') + }) + + it('should allow explicit column selection for non-admin', async () => { + const plugin = new SqlMacrosPlugin({ preventSelectStar: true }) + plugin.config = userConfig + + const res = await plugin.beforeQuery({ + sql: 'SELECT id, email FROM users', + dataSource: mockInternalDataSource, + config: userConfig, + }) + expect(res.sql).toBe('SELECT id, email FROM users') + }) + }) + + describe('$_exclude column macro replacement', () => { + it('should bypass non-internal data sources', async () => { + const plugin = new SqlMacrosPlugin({ preventSelectStar: false }) + const sql = 'SELECT id, $_exclude(password) FROM users' + const res = await plugin.beforeQuery({ + sql, + dataSource: mockExternalDataSource, + config: userConfig, + }) + expect(res.sql).toBe(sql) + }) + + it('should replace $_exclude with remaining table columns on internal SQLite data source', async () => { + const executeQueryMock = vi.fn().mockResolvedValue([ + { column_name: 'id' }, + { column_name: 'username' }, + { column_name: 'email' }, + { column_name: 'password' }, + ]) + + const ds: DataSource = { + name: 'test-db', + source: 'internal', + type: 'sqlite', + rpc: { executeQuery: executeQueryMock } as any, + } + + const plugin = new SqlMacrosPlugin({ preventSelectStar: false }) + const res = await plugin.beforeQuery({ + sql: 'SELECT $_exclude(password) FROM users;', + dataSource: ds, + config: userConfig, + }) + + expect(executeQueryMock).toHaveBeenCalledWith( + expect.objectContaining({ + sql: expect.stringContaining("pragma_table_info('users')"), + }) + ) + expect(res.sql.toLowerCase()).toContain('id') + expect(res.sql.toLowerCase()).toContain('username') + expect(res.sql.toLowerCase()).toContain('email') + expect(res.sql.toLowerCase()).not.toContain('password') + }) + + it('should ignore pragma_table_info queries', async () => { + const plugin = new SqlMacrosPlugin({ preventSelectStar: false }) + const pragmaSql = "SELECT name FROM pragma_table_info('users')" + const res = await plugin.beforeQuery({ + sql: pragmaSql, + dataSource: mockInternalDataSource, + config: userConfig, + }) + expect(res.sql).toBe(pragmaSql) + }) + }) +}) diff --git a/src/allowlist/index.test.ts b/src/allowlist/index.test.ts new file mode 100644 index 0000000..8647a57 --- /dev/null +++ b/src/allowlist/index.test.ts @@ -0,0 +1,166 @@ +import { describe, expect, it, vi } from 'vitest' +import { isQueryAllowed } from './index' +import { DataSource } from '../types' +import { StarbaseDBConfiguration } from '../handler' + +describe('isQueryAllowed', () => { + const mockDataSource: DataSource = { + name: 'test-db', + source: 'internal', + type: 'sqlite', + rpc: { + executeQuery: vi.fn(), + } as any, + } + + const mockConfig: StarbaseDBConfiguration = { + role: 'user', + } as any + + it('should allow query when isEnabled is false', async () => { + const result = await isQueryAllowed({ + sql: 'SELECT * FROM users', + isEnabled: false, + dataSource: mockDataSource, + config: mockConfig, + }) + expect(result).toBe(true) + }) + + it('should allow any query when user has admin role', async () => { + const adminConfig: StarbaseDBConfiguration = { + role: 'admin', + } as any + const result = await isQueryAllowed({ + sql: 'DROP TABLE users', + isEnabled: true, + dataSource: mockDataSource, + config: adminConfig, + }) + expect(result).toBe(true) + }) + + it('should throw error when sql is empty', async () => { + await expect( + isQueryAllowed({ + sql: '', + isEnabled: true, + dataSource: mockDataSource, + config: mockConfig, + }) + ).rejects.toThrow('No SQL provided for allowlist check') + }) + + it('should allow matching query in allowlist', async () => { + const ds: DataSource = { + name: 'test-db', + source: 'internal', + type: 'sqlite', + rpc: { + executeQuery: vi.fn().mockResolvedValue([ + { + sql_statement: 'SELECT id, name FROM users WHERE id = 1', + source: 'internal', + }, + ]), + } as any, + } + + const result = await isQueryAllowed({ + sql: 'SELECT id, name FROM users WHERE id = 1;', + isEnabled: true, + dataSource: ds, + config: mockConfig, + }) + expect(result).toBe(true) + }) + + it('should handle whitespace and semicolon normalization', async () => { + const ds: DataSource = { + name: 'test-db', + source: 'internal', + type: 'sqlite', + rpc: { + executeQuery: vi.fn().mockResolvedValue([ + { + sql_statement: 'SELECT id FROM users;', + source: 'internal', + }, + ]), + } as any, + } + + const result = await isQueryAllowed({ + sql: ' SELECT id FROM users ', + isEnabled: true, + dataSource: ds, + config: mockConfig, + }) + expect(result).toBe(true) + }) + + it('should reject unlisted query and record rejection', async () => { + const executeQueryMock = vi.fn().mockImplementation(async ({ sql }) => { + if (sql.includes('SELECT sql_statement')) { + return [ + { + sql_statement: 'SELECT id FROM allowed_table', + source: 'internal', + }, + ] + } + if (sql.includes('INSERT INTO tmp_allowlist_rejections')) { + return [{ sql_statement: 'SELECT * FROM forbidden' }] + } + return [] + }) + + const ds: DataSource = { + name: 'test-db', + source: 'internal', + type: 'sqlite', + rpc: { executeQuery: executeQueryMock } as any, + } + + await expect( + isQueryAllowed({ + sql: 'SELECT * FROM forbidden', + isEnabled: true, + dataSource: ds, + config: mockConfig, + }) + ).rejects.toThrow('Query not allowed') + + expect(executeQueryMock).toHaveBeenCalledWith( + expect.objectContaining({ + sql: expect.stringContaining('INSERT INTO tmp_allowlist_rejections'), + params: ['SELECT * FROM forbidden', 'internal'], + }) + ) + }) + + it('should isolate queries by dataSource source', async () => { + const ds: DataSource = { + name: 'external-db', + source: 'external-1', + type: 'postgres', + rpc: { + executeQuery: vi.fn().mockResolvedValue([ + { + sql_statement: 'SELECT count(*) FROM items', + source: 'internal', // Different source + }, + ]), + } as any, + } + + await expect( + isQueryAllowed({ + sql: 'SELECT count(*) FROM items', + isEnabled: true, + dataSource: ds, + config: mockConfig, + }) + ).rejects.toThrow('Query not allowed') + }) +}) diff --git a/src/allowlist/index.ts b/src/allowlist/index.ts index 71c12e3..ffdcc41 100644 --- a/src/allowlist/index.ts +++ b/src/allowlist/index.ts @@ -73,7 +73,7 @@ export async function isQueryAllowed(opts: { try { if (!sql) { - return Error('No SQL provided for allowlist check') + throw new Error('No SQL provided for allowlist check') } const normalizedQuery = parser.astify(normalizeSQL(sql))