Skip to content

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

6.7 KB
Raw Blame
import type { DbConn } from './appdb'
import type { Store } from './db'
import { authFailure, DbReaders, readerUrl } from './dbreader'
import { fail, UpstreamError } from './errors'
import type { NeonClient } from './neon'
import { READER_ROLE } from './sqlguard'

const owner = 'postgresql://[email protected]/db?sslmode=require'
const branch = 'branch-main'
const project = 'app-project'
const password = 'test:/@value'
function provisioner(systemWorker = false) {
  const store = {
    organizationId: systemWorker ? undefined : '9039b144-50a8-494e-ad67-c5e18cc203f2',
    all: jest.fn(async () => [{ app_id: 'app', db_url: owner, neon_branch_id: branch }]),
    appById: jest.fn(async () => ({ neon_project_id: project })),
    get: jest.fn(async (): Promise<{ password: string } | undefined> => undefined),
    run: jest.fn(async () => undefined),
  }
  const neon = {
    getRole: jest.fn(async (): Promise<{ authMethod: string } | undefined> => undefined),
    deleteRole: jest.fn(async () => undefined),
    createRole: jest.fn(async () => 'created'),
    revealRolePassword: jest.fn(async () => password),
  }
  const ownerConn = { query: jest.fn(async () => ({ rows: [] })), end: jest.fn(async () => undefined) }
  const readerConn = { query: jest.fn(async () => ({ rows: [{ ok: true }] })), end: jest.fn(async () => undefined) }
  const connect = jest.fn(async (url: string) => (url === owner ? ownerConn : readerConn) as unknown as DbConn)
  const log = jest.fn()
  const readers = new DbReaders({
    store: store as unknown as Store,
    neon: neon as unknown as NeonClient,
    connect,
    ...(systemWorker ? {} : { log, retryMs: 0 }),
  })
  return { readers, store, neon, connect, ownerConn, readerConn, log }
}

it('uses the branch cache without contacting Neon and preserves the owner URL options', async () => {
  const { readers, store, neon, connect } = provisioner()
  store.get.mockResolvedValue({ password })
  const login = new URL(await readers.urlFor(owner))
  expect(login.username).toBe(READER_ROLE)
  expect(decodeURIComponent(login.password)).toBe(password)
  expect(login.pathname).toBe('/db')
  expect(login.searchParams.get('sslmode')).toBe('require')
  expect(store.get).toHaveBeenCalledWith(expect.any(String), project, branch)
  expect(connect).not.toHaveBeenCalled()
  expect(neon.getRole).not.toHaveBeenCalled()
})

it('shares concurrent provisioning and caches the credentials after verifying access', async () => {
  const { readers, neon, store, ownerConn, readerConn, log } = provisioner()
  neon.revealRolePassword.mockRejectedValueOnce(new UpstreamError('Neon', 404, 'branch is starting'))
  readerConn.query
    .mockImplementationOnce(async () => ({ rows: [] }))
    .mockImplementationOnce(async () => ({ rows: [] }))
    .mockImplementationOnce(async () => ({ rows: [] }))
    .mockImplementationOnce(async () => ({ rows: [{ ok: false }] }))
  expect(await Promise.all([readers.urlFor(owner), readers.refresh(owner)])).toEqual([
    readerUrl(owner, password),
    readerUrl(owner, password),
  ])
  expect(neon.createRole).toHaveBeenCalledTimes(1)
  expect(neon.revealRolePassword).toHaveBeenCalledTimes(2)
  expect(ownerConn.query).toHaveBeenCalledWith(`GRANT pg_read_all_data TO ${READER_ROLE}`)
  expect(ownerConn.end).toHaveBeenCalledTimes(2)
  expect(readerConn.query).toHaveBeenCalledWith(`ALTER ROLE ${READER_ROLE} SET default_transaction_read_only = on`)
  expect(readerConn.end).toHaveBeenCalledTimes(2)
  expect(store.run).toHaveBeenCalledWith(
    expect.stringContaining('INSERT INTO db_readers'),
    project,
    branch,
    password,
    expect.any(String),
  )
  expect(log.mock.calls.flat().join(' ')).not.toContain(password)
})

it.each([true, false])('clears the old reader cache when Neon deletion succeeds=%s', async (apiDeletes) => {
  const { readers, neon, store, ownerConn } = provisioner()
  neon.getRole.mockResolvedValue({ authMethod: 'no_login' })
  if (!apiDeletes) neon.deleteRole.mockRejectedValue(new Error('role unavailable through API'))
  await readers.refresh(owner)
  expect(neon.deleteRole).toHaveBeenCalledWith(project, branch, READER_ROLE)
  if (apiDeletes) expect(ownerConn.query).not.toHaveBeenCalledWith(`DROP ROLE ${READER_ROLE}`)
  else expect(ownerConn.query).toHaveBeenCalledWith(`DROP ROLE ${READER_ROLE}`)
  expect(store.run).toHaveBeenCalledWith(expect.stringContaining('DELETE FROM db_readers'), project, branch)
})

it('refuses unknown branches and allows a failed refresh to be retried', async () => {
  const { readers, neon, store } = provisioner()
  await expect(readers.urlFor('postgresql://[email protected]/db')).rejects.toMatchObject({
    code: 'unavailable',
  })
  const failed = fail('unavailable', 'provider unavailable')
  neon.createRole.mockRejectedValueOnce(failed)
  await expect(readers.refresh(owner)).rejects.toBe(failed)
  expect(store.run).not.toHaveBeenCalled()
  await expect(readers.refresh(owner)).resolves.toBe(readerUrl(owner, password))
})

it('stops when the reader grant never reaches the compute and leaves the cache empty', async () => {
  const { readers, readerConn, store } = provisioner()
  readerConn.query.mockResolvedValue({ rows: [{ ok: false }] })
  await expect(readers.refresh(owner)).rejects.toMatchObject({
    code: 'unavailable',
    message: expect.stringContaining('does not hold pg_read_all_data'),
  })
  expect(readerConn.end).toHaveBeenCalledTimes(6)
  expect(store.run).not.toHaveBeenCalled()
})

it.each([
  [{ code: '28P01' }, true],
  [{ code: '28000' }, true],
  [{ message: 'role "boxlite_reader" does not exist' }, true],
  [{ code: '08006', message: 'connection lost' }, false],
])('identifies reader login failures from %j', (error, expected) => {
  expect(authFailure(error)).toBe(expected)
})

it('refreshes an existing role for the system worker and reports readiness without revealing the login', async () => {
  const { readers, store, neon, readerConn } = provisioner(true)
  const log = jest.spyOn(console, 'log').mockImplementation(() => undefined)
  jest.useFakeTimers()
  try {
    neon.createRole.mockResolvedValue('exists')
    let grantVisible = false
    readerConn.query.mockImplementation(async (sql?: string) => {
      if (sql?.includes('pg_has_role') && !grantVisible) {
        grantVisible = true
        return { rows: [{ ok: false }] }
      }
      return { rows: [{ ok: true }] }
    })
    const pending = readers.refresh(owner)
    await jest.runAllTimersAsync()
    expect(await pending).toBe(readerUrl(owner, password))
    expect(readerConn.end).toHaveBeenCalledTimes(2)
    expect(store.all).toHaveBeenCalledWith(expect.any(String), null, null)
    expect(log).toHaveBeenCalledWith(`[db-reader] ${READER_ROLE} ready on ${project}/${branch} (already there)`)
    expect(authFailure({})).toBe(false)
  } finally {
    log.mockRestore()
    jest.useRealTimers()
  }
})