Skip to content
Open
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
135 changes: 135 additions & 0 deletions src/allowlist/index.test.ts
Original file line number Diff line number Diff line change
@@ -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')
})
})
82 changes: 82 additions & 0 deletions src/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
})
163 changes: 163 additions & 0 deletions src/import/csv.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
Loading