Skip to content

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

4.8 KB
Raw Blame
import { EventEmitter } from 'node:events'
import { PassThrough } from 'node:stream'
import { runSession } from './session'
import * as pgwire from './pgwire'
import type { WsConn } from './websocket'

function setup(write = false) {
  const ws = Object.assign(new EventEmitter(), {
    send: jest.fn((_bytes: Buffer) => true),
    close: jest.fn(),
    pause: jest.fn(),
    resume: jest.fn(),
    socket: new EventEmitter(),
  })
  const target = {
    appId: 'app',
    write,
    main: true,
    login: jest.fn(async (_refresh: boolean) => 'postgresql://user@localhost/test'),
    onOpen: jest.fn(),
    onClose: jest.fn(),
  }
  runSession(ws as unknown as WsConn, target)
  return { ws, target, start: (params: Record<string, string> = {}) => ws.emit('data', pgwire.startupPacket(params)) }
}
const flush = () => new Promise<void>((r) => setImmediate(r))
function serverMessage(bytes: Buffer) {
  const reader = new pgwire.MessageReader()
  reader.push(bytes)
  return reader.next()!
}
function upstream() {
  return { socket: new PassThrough(), pid: 20, secret: 30, greeting: [pgwire.readyForQuery()], rest: Buffer.alloc(0) }
}
describe('PostgreSQL client startup over the database tunnel', () => {
  afterEach(() => jest.restoreAllMocks())
  it.each([pgwire.SSL_REQUEST, pgwire.GSSENC_REQUEST])(
    'declines protocol encryption negotiation %i on an already encrypted connection',
    (code) => {
      const { ws, target } = setup()
      const packet = Buffer.alloc(8)
      packet.writeInt32BE(8)
      packet.writeInt32BE(code, 4)
      ws.emit('data', packet.subarray(0, 3))
      expect(ws.send).not.toHaveBeenCalled()
      ws.emit('data', packet.subarray(3))
      expect(ws.send).toHaveBeenCalledWith(Buffer.from('N'))
      expect(target.login).not.toHaveBeenCalled()
    },
  )
  it.each([
    ['reader', false, 2],
    ['owner', true, 1],
  ] as const)('refreshes only a reader credential following refused %s login', async (_name, write, tries) => {
    const { ws, target, start } = setup(write)
    const db = upstream()
    const connect = jest
      .spyOn(pgwire, 'connectUpstream')
      .mockRejectedValueOnce(new pgwire.PgError({ C: '28P01', M: 'login refused' }))
      .mockResolvedValue(db as unknown as pgwire.Upstream)
    start({ application_name: 'orm', client_encoding: 'UTF8' })
    await flush()
    expect(target.login.mock.calls).toEqual(write ? [[false]] : [[false], [true]])
    expect(connect).toHaveBeenCalledTimes(tries)
    if (write) {
      const error = serverMessage(ws.send.mock.calls[0][0])
      expect(pgwire.errorFields(error.body)).toMatchObject({ C: '28P01', M: 'login refused', S: 'FATAL' })
      expect(target.onOpen).not.toHaveBeenCalled()
    } else {
      expect(target.onOpen).toHaveBeenCalled()
      ws.emit('close')
      expect(target.onClose).toHaveBeenCalledWith({ statements: 0, refused: 0 })
    }
    db.socket.destroy()
  })
  it('closes a completed upstream login when the client disconnects during authentication', async () => {
    const { ws, target, start } = setup()
    let accept!: (v: pgwire.Upstream) => void
    jest.spyOn(pgwire, 'connectUpstream').mockImplementation(
      () =>
        new Promise((r) => {
          accept = r
        }),
    )
    start()
    await flush()
    ws.emit('close')
    const db = upstream()
    accept(db as unknown as pgwire.Upstream)
    await flush()
    expect(db.socket.destroyed).toBe(true)
    expect(target.onOpen).not.toHaveBeenCalled()
  })
  it('explains a database connection failure using a PostgreSQL fatal error', async () => {
    const { ws, start } = setup()
    jest.spyOn(pgwire, 'connectUpstream').mockRejectedValue(new Error('no route to database'))
    start()
    await flush()
    expect(pgwire.errorFields(serverMessage(ws.send.mock.calls[0][0]).body)).toMatchObject({
      C: '08006',
      M: expect.stringContaining('no route to database'),
    })
    expect(ws.close).toHaveBeenCalled()
  })
  it('negotiates supported protocol options before opening the database session', async () => {
    const { ws, target } = setup()
    const db = upstream()
    jest.spyOn(pgwire, 'connectUpstream').mockResolvedValue(db as unknown as pgwire.Upstream)
    const packet = pgwire.startupPacket({ '_pq_.feature': 'unused' })
    ws.emit('data', packet)
    await flush()
    expect(target.onOpen).toHaveBeenCalled()
    expect(serverMessage(ws.send.mock.calls[0][0]).type).toBe('v')
    ws.emit('close')
  })
  it.each([
    [pgwire.startupPacket({ replication: 'database' }), '42501'],
    [Buffer.from([0, 0, 0, 8, 0, 2, 0, 0]), '0A000'],
    [Buffer.from([0, 0, 0, 4]), '08P01'],
  ] as const)('refuses a startup packet outside the supported session contract', (packet, code) => {
    const { ws, target } = setup()
    ws.emit('data', packet)
    expect(pgwire.errorFields(serverMessage(ws.send.mock.calls[0][0]).body)).toMatchObject({ C: code, S: 'FATAL' })
    expect(target.login).not.toHaveBeenCalled()
  })
})