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
182 changes: 182 additions & 0 deletions src/allowlist/index.test.ts
Original file line number Diff line number Diff line change
@@ -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()
})
})
169 changes: 168 additions & 1 deletion src/do.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand All @@ -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

Expand Down Expand Up @@ -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)
})
})
Loading