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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions plugins/resend/index.test.ts
Original file line number Diff line number Diff line change
@@ -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',
'<p>Hello World</p>'
)

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: '<p>Hello World</p>',
}),
})
})

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')
})
})
141 changes: 141 additions & 0 deletions plugins/sql-macros/index.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
})
166 changes: 166 additions & 0 deletions src/allowlist/index.test.ts
Original file line number Diff line number Diff line change
@@ -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')
})
})
2 changes: 1 addition & 1 deletion src/allowlist/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down