Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

18.1 KB
Raw Blame
import { Readable } from 'node:stream'
import { text } from 'node:stream/consumers'
import { jsonPost, managementHttp, principal } from '../../../../test/cloud-app/management'
import type { AppDatabase, QueryResult } from '../appdb'
import type { Ctx } from '../ctx'
import { ensureSqlParser } from '../sqlguard'
import { fail } from '../errors'

const dbPath = '/v1/apps/journal/envs/main/db'
const previewPath = '/v1/apps/journal/envs/preview/db'
const url = 'postgres://[email protected]/journal'

function result(rows: unknown[][], columns: string[] = []): QueryResult {
  return { columns, rows, row_count: rows.length, elapsed_ms: 1, truncated: false }
}

function databaseFixture() {
  const app = { id: 'app', name: 'journal', org_id: 'org', neon_project_id: 'project' }
  const main = { id: 'main-env', name: 'main', db_url: url as string | null, neon_branch_id: 'branch' as string | null }
  const preview = { ...main, id: 'preview-env', name: 'preview', neon_branch_id: 'preview-branch' }
  const store = {
    appByName: async (name: string) => (name === app.name ? app : undefined),
    envByName: async (_id: string, name: string) => [main, preview].find((env) => env.name === name),
    recordActivity: jest.fn(),
    deploymentsWhere: jest.fn().mockResolvedValue([]),
    get: jest.fn(),
    all: jest.fn().mockResolvedValue([]),
    run: jest.fn(),
  }
  const appdb = {
    query: jest.fn<ReturnType<AppDatabase['query']>, Parameters<AppDatabase['query']>>(),
    listApplied: jest.fn().mockResolvedValue([]),
    exportCsv: jest.fn(),
    exportSql: jest.fn(),
    importCsv: jest.fn(),
  }
  const neon = { getBranch: jest.fn().mockResolvedValue({ logicalSizeBytes: 8192 }), restoreBranch: jest.fn() }
  const request = managementHttp({ config: {}, store, appdb, neon } as unknown as Ctx)
  return { request, appdb, store, main, neon }
}

describe('App database management HTTP API', () => {
  beforeAll(() => ensureSqlParser())

  it('reports connection coordinates, including a branch that cannot report its size', async () => {
    const { request, main, neon } = databaseFixture()
    expect(await (await request(dbPath)).json()).toEqual({
      status: 'ready',
      host: 'branch.example.test',
      database: 'journal',
      user: 'owner',
      branch: 'branch',
      size_bytes: 8192,
    })
    expect(neon.getBranch).toHaveBeenCalledWith('project', 'branch')
    neon.getBranch.mockRejectedValueOnce(new Error('branch unavailable'))
    expect(await (await request(dbPath)).json()).toMatchObject({ status: 'unknown', size_bytes: null })
    main.db_url = null
    expect(await (await request(dbPath)).json()).toEqual({ status: 'none' })
    expect((await request(dbPath + '/schema')).status).toBe(404)
  })

  it('groups schema columns by table and shows indexes, constraints and a numeric estimate for one table', async () => {
    const { request, appdb } = databaseFixture()
    const columns = [
      ['id', 'integer', 'NO', null],
      ['note', 'text', 'YES', null],
    ]
    appdb.query.mockResolvedValueOnce(result(columns.map((col) => ['entries', ...col])))
    const expected = [
      { name: 'id', type: 'integer', nullable: false, default: null },
      { name: 'note', type: 'text', nullable: true, default: null },
    ]
    expect(await (await request(dbPath + '/schema')).json()).toEqual({
      tables: [{ name: 'entries', columns: expected }],
    })
    appdb.query
      .mockResolvedValueOnce(result(columns))
      .mockResolvedValueOnce(result([['idx', 'INDEX entries(id)']]))
      .mockResolvedValueOnce(result([['pk', 'PRIMARY KEY (id)']]))
      .mockResolvedValueOnce(result([['14']]))
    expect(await (await request(dbPath + '/schema/entries')).json()).toEqual({
      name: 'entries',
      columns: expected,
      indexes: [{ name: 'idx', definition: 'INDEX entries(id)' }],
      constraints: [{ name: 'pk', definition: 'PRIMARY KEY (id)' }],
      row_estimate: 14,
    })
    for (const call of appdb.query.mock.calls.slice(1)) expect(call[2]).toEqual({ params: ['entries'], write: false })
    appdb.query.mockResolvedValueOnce(result([]))
    expect((await request(dbPath + '/schema/missing')).status).toBe(404)
  })

  it('binds pagination for a filtered row page and rejects unknown tables and malformed expressions', async () => {
    const { request, appdb } = databaseFixture()
    appdb.query.mockResolvedValueOnce(result([[1]])).mockResolvedValueOnce(result([[7]], ['id']))
    const response = await request(dbPath + '/rows/entries?limit=3000&offset=-1&where=id%3D7')
    expect(await response.json()).toMatchObject({ limit: 1000, offset: 0, rows: [[7]], columns: ['id'] })
    expect(appdb.query).toHaveBeenLastCalledWith(
      url,
      ['SELECT * FROM public."entries" WHERE id=7 LIMIT $1 OFFSET $2'],
      {
        params: [1000, 0],
        write: false,
      },
    )
    appdb.query.mockResolvedValueOnce(result([[1]])).mockResolvedValueOnce(result([]))
    expect(await (await request(dbPath + '/rows/entries')).json()).toMatchObject({ limit: 50, offset: 0, rows: [] })
    appdb.query.mockResolvedValueOnce(result([]))
    expect((await request(dbPath + '/rows/missing')).status).toBe(404)
    appdb.query.mockResolvedValueOnce(result([[1]]))
    expect((await request(dbPath + '/rows/entries?where=%28')).status).toBe(400)
  })

  it.each([
    [dbPath, { query: 'SELECT (' }, 400, 'sql_error'],
    [dbPath, { query: 'CREATE TABLE notes (id integer)', write: true }, 403, 'forbidden'],
    [previewPath, { query: 'CREATE TABLE notes (id integer)' }, 403, 'forbidden'],
    [dbPath, { query: 'DELETE FROM entries' }, 403, 'write_requires_flag'],
    [dbPath, { query: 'SELECT 1; SELECT 2', explain: true }, 400, 'invalid_request'],
    [dbPath, { query: 'BEGIN' }, 403, 'forbidden'],
  ])('checks SQL before sending %j %j to PostgreSQL', async (base, input, status, code) => {
    const { request, appdb } = databaseFixture()
    const response = await request(base + '/sql', jsonPost(input))
    expect({ status: response.status, body: await response.json() }).toMatchObject({
      status,
      body: { error: { code } },
    })
    expect(appdb.query).not.toHaveBeenCalled()
  })

  it('explains writes read-only, checks explicit write scope and audits accepted preview DDL', async () => {
    const { request, appdb, store } = databaseFixture()
    appdb.query.mockResolvedValue(result([['Delete on entries']]))
    expect((await request(dbPath + '/sql', jsonPost({ query: 'DELETE FROM entries', explain: true }))).status).toBe(200)
    expect(appdb.query).toHaveBeenCalledWith(url, ['EXPLAIN (FORMAT TEXT) DELETE FROM entries'], { write: false })
    const input = jsonPost({ query: 'CREATE TABLE notes (id integer)', write: true })
    expect((await request(previewPath + '/sql', input, { ...principal, permissions: ['read:apps'] })).status).toBe(403)
    expect((await request(previewPath + '/sql', input)).status).toBe(200)
    expect(appdb.query).toHaveBeenLastCalledWith(url, ['CREATE TABLE notes (id integer)'], { write: true })
    expect(store.recordActivity).toHaveBeenCalledWith('app', 'preview', principal.actor, 'db.sql.write', {
      statements: ['CREATE'],
    })
  })

  it('exports a named table or the whole database with download headers and audit details', async () => {
    const { request, appdb, store } = databaseFixture()
    appdb.query.mockResolvedValue(result([['entries']]))
    appdb.exportCsv.mockResolvedValue(Readable.from([Buffer.from('id\n1\n')]))
    appdb.exportSql.mockResolvedValue(Readable.from([Buffer.from('CREATE TABLE entries (id int);')]))
    const csv = await request(dbPath + '/export?table=entries')
    expect(csv.headers.get('content-disposition')).toBe('attachment; filename="journal-main-entries.csv"')
    expect(await csv.text()).toBe('id\n1\n')
    expect(appdb.exportCsv).toHaveBeenCalledWith(url, 'entries')
    const sql = await request(dbPath + '/export')
    expect(sql.headers.get('content-type')).toContain('application/sql')
    expect(await sql.text()).toContain('CREATE TABLE entries')
    expect(appdb.exportSql).toHaveBeenCalledWith(url, {
      title: 'BoxLite database export of journal/main',
      table: undefined,
    })
    expect(store.recordActivity).toHaveBeenCalledWith('app', 'main', principal.actor, 'db.export', {
      format: 'sql',
      table: null,
    })
    expect((await request(dbPath + '/export?table=missing')).status).toBe(404)
  })

  it('imports validated CSV with its original header and records a restore point before writing', async () => {
    const { request, appdb, store } = databaseFixture()
    appdb.query.mockResolvedValueOnce(result([['entries']])).mockResolvedValueOnce(result([['id'], ['note']]))
    const payload = 'id,note\r\n1,first\r\n'
    appdb.importCsv.mockImplementation(async (db, table, columns, stream) => {
      expect(store.run).toHaveBeenCalledWith(
        expect.stringContaining('INSERT INTO db_snapshots'),
        expect.any(String),
        'main-env',
        'before import into entries',
        expect.any(String),
        principal.actor,
      )
      expect([db, table, columns, await text(stream)]).toEqual([url, 'entries', ['id', 'note'], payload])
      return 1
    })
    const response = await request(dbPath + '/import?table=entries', { method: 'POST', body: payload })
    const imported = await response.json()
    expect(imported).toEqual({
      snapshot: expect.stringMatching(/^dbs_/),
      table: 'entries',
      rows: 1,
      columns: ['id', 'note'],
    })
    expect(store.recordActivity).toHaveBeenCalledWith('app', 'main', principal.actor, 'db.import', imported)
  })

  it('rejects unsupported formats and invalid imports before creating a restore point', async () => {
    const { request, appdb, store } = databaseFixture()
    expect((await request(dbPath + '/export?format=json')).status).toBe(400)
    expect((await request(dbPath + '/export?format=csv')).status).toBe(400)
    expect((await request(dbPath + '/import', { method: 'POST' })).status).toBe(400)
    expect((await request(dbPath + '/import?table=entries', { method: 'POST' })).status).toBe(400)
    appdb.query.mockResolvedValueOnce(result([]))
    const missing = await request(dbPath + '/export?table=entries')
    expect(await missing.json()).toMatchObject({
      error: { code: 'not_found', next: expect.stringContaining('no tables yet') },
    })
    appdb.query.mockResolvedValueOnce(result([['entries']]))
    const empty = await request(dbPath + '/import?table=entries', { method: 'POST', body: '\n' })
    expect(await empty.json()).toMatchObject({
      error: { code: 'invalid_request', message: 'the CSV has no header row' },
    })
    appdb.query.mockResolvedValueOnce(result([['entries']])).mockResolvedValueOnce(result([['id']]))
    const invalid = await request(dbPath + '/import?table=entries', { method: 'POST', body: 'typo\n1\n' })
    expect(await invalid.json()).toMatchObject({
      error: { code: 'invalid_request', message: expect.stringContaining('typo') },
    })
    expect(store.run).not.toHaveBeenCalled()
    expect(appdb.importCsv).not.toHaveBeenCalled()
    Reflect.deleteProperty(appdb, 'importCsv')
    expect((await request(dbPath + '/export')).status).toBe(503)
  })

  it('merges the latest migration files with applied history in filename order', async () => {
    const { request, appdb, store } = databaseFixture()
    store.deploymentsWhere.mockResolvedValue([
      {
        request: {
          resolved_migrations: [
            { file: '003', sha256: 'new' },
            { file: '002', sha256: 'next' },
            { file: '001', sha256: 'same' },
          ],
        },
      },
    ])
    const history = { deployment: 3, applied_at: '2026-01-02T00:00:00Z' }
    appdb.listApplied.mockResolvedValue([
      { file: '000', sha256: 'old', ...history },
      { file: '001', sha256: 'same', ...history },
      { file: '003', sha256: 'old', ...history },
    ])
    expect(await (await request(dbPath + '/migrations')).json()).toEqual([
      { file: '000', status: 'applied', ...history },
      { file: '001', status: 'applied', ...history },
      { file: '002', status: 'pending' },
      { file: '003', status: 'changed', ...history },
    ])
  })

  it('creates a named snapshot and restores its stored timestamp on the selected branch', async () => {
    const { request, store, neon } = databaseFixture()
    const response = await request(dbPath + '/snapshots', jsonPost({ message: 'before editing' }))
    expect(response.status).toBe(201)
    const snap = await response.json()
    expect(snap).toEqual({
      id: expect.stringMatching(/^dbs_/),
      message: 'before editing',
      ts: snap.created_at,
      created_at: expect.any(String),
      by: principal.actor,
    })
    expect(store.run).toHaveBeenCalledWith(
      expect.stringContaining('INSERT INTO db_snapshots'),
      snap.id,
      'main-env',
      snap.message,
      snap.ts,
      snap.by,
    )
    store.get.mockResolvedValueOnce({ ts: snap.ts })
    const unnamed = await (await request(dbPath + '/snapshots', jsonPost({}))).json()
    expect(unnamed.message).toBeNull()
    const restored = await (await request(dbPath + '/restore', jsonPost({ snapshot: snap.id }))).json()
    expect(store.get).toHaveBeenCalledWith(expect.stringContaining('AND env_id = ?'), snap.id, 'main-env')
    expect(restored).toEqual({ restored_to: snap.ts, preserved_as: expect.stringMatching(/^main-before-restore-/) })
    expect(neon.restoreBranch).toHaveBeenCalledWith('project', 'branch', snap.ts, restored.preserved_as)
    expect((await request(previewPath + '/restore', jsonPost({ snapshot: snap.id }))).status).toBe(404)
  })

  it('normalizes restore timestamps and rejects missing, invalid and future restore points', async () => {
    const { request, neon } = databaseFixture()
    for (const invalid of [{}, { to: 'tomorrow' }, { to: '2999-01-01' }]) {
      expect((await request(dbPath + '/restore', jsonPost(invalid))).status).toBe(400)
    }
    expect(neon.restoreBranch).not.toHaveBeenCalled()
    expect(await (await request(dbPath + '/restore', jsonPost({ to: '2025-01-01' }))).json()).toMatchObject({
      restored_to: '2025-01-01T00:00:00.000Z',
    })
  })
})

describe('Console database views', () => {
  beforeAll(() => ensureSqlParser())

  it('joins table counts to names and projects backups and migrations for the dashboard', async () => {
    const { request, appdb, main, store } = databaseFixture()
    appdb.query.mockResolvedValueOnce(result([['entries'], ['tags']])).mockResolvedValueOnce(
      result([
        ['tags', '9'],
        ['entries', '2'],
      ]),
    )
    store.all.mockResolvedValue([{ id: 'snapshot', message: 'before deploy', by: 'key:1234' }])
    expect(await (await request(dbPath + '/view')).json()).toMatchObject({
      status: 'ready',
      engine: 'Postgres',
      name: 'journal',
      sizeBytes: 8192,
      tables: [
        { schema: 'public', name: 'entries', rows: 2 },
        { schema: 'public', name: 'tags', rows: 9 },
      ],
      backups: [{ id: 'snapshot', by: 'key 1234' }],
      migrations: [],
      restoreWindowHours: 6,
      errors: [],
    })
    main.db_url = null
    expect(await (await request(dbPath + '/view')).json()).toEqual({ status: 'none' })
  })

  it('shows a database with no provisioned branch or available backup listing', async () => {
    const { request, main, appdb, neon, store } = databaseFixture()
    appdb.query.mockResolvedValue(result([]))
    neon.getBranch.mockRejectedValueOnce(new Error('size unavailable'))
    store.all.mockRejectedValueOnce(fail('unavailable', 'snapshots unavailable'))
    expect(await (await request(dbPath + '/view')).json()).toMatchObject({
      status: 'unknown',
      sizeBytes: null,
      backups: null,
      errors: ['snapshots unavailable'],
    })
    main.neon_branch_id = null
    expect(await (await request(dbPath + '/view')).json()).toEqual({ status: 'none' })
    appdb.listApplied.mockClear()
    main.db_url = null
    expect(await (await request(dbPath + '/migrations')).json()).toEqual([])
    expect(appdb.listApplied).not.toHaveBeenCalled()
  })

  it('keeps metadata and backups visible when reading the migration ledger fails', async () => {
    const { request, appdb } = databaseFixture()
    appdb.query.mockResolvedValueOnce(result([]))
    appdb.listApplied.mockRejectedValueOnce(fail('unavailable', 'database is starting'))
    expect(await (await request(dbPath + '/view')).json()).toMatchObject({
      status: 'ready',
      tables: [],
      backups: [],
      migrations: null,
      errors: ['database is starting'],
    })
  })

  it('shows default pagination and returns unknown column types as null', async () => {
    const { request, appdb } = databaseFixture()
    appdb.query.mockImplementation(async (_url, [sql]) => {
      if (sql!.includes('SELECT 1 FROM information_schema.tables')) return result([[1]])
      if (sql!.startsWith('SELECT * FROM')) return result([[null]], ['value'])
      if (sql!.includes('count(*)')) return result([['1']])
      return result([])
    })
    expect(await (await request(dbPath + '/rows/entries/view')).json()).toEqual({
      limit: 20,
      offset: 0,
      total: 1,
      rows: [[null]],
      columns: ['value'],
      types: [null],
    })
    expect(appdb.query.mock.calls.every((call) => !call[1][0]?.includes('ILIKE'))).toBe(true)
  })

  it('combines a searched row page with its total and PostgreSQL column types', async () => {
    const { request, appdb } = databaseFixture()
    appdb.query.mockImplementation(async (_url, [sql]) => {
      if (sql!.includes('SELECT 1 FROM information_schema.tables')) return result([[1]])
      if (sql!.startsWith('SELECT * FROM')) return result([[42, { title: 'entry' }]], ['id', 'payload'])
      if (sql!.includes('count(*)')) return result([['9']])
      if (sql!.includes('column_name, data_type'))
        return result([
          ['id', 'integer'],
          ['payload', 'jsonb'],
        ])
      throw new Error('unexpected query: ' + sql)
    })
    const response = await request(dbPath + '/rows/entries/view?limit=300&offset=3&search=entry')
    expect(await response.json()).toEqual({
      columns: ['id', 'payload'],
      types: ['integer', 'jsonb'],
      rows: [[42, '{"title":"entry"}']],
      limit: 200,
      offset: 3,
      total: 9,
    })
    expect(appdb.query.mock.calls.filter((call) => call[1][0]?.includes('ILIKE'))).toHaveLength(2)
  })
})