Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript
5.6 KB
Raw Blame
import { expect, it } from 'vitest'
import { once } from 'node:events'
import { type Socket, createConnection, createServer } from 'node:net'
import { setImmediate as nextTurn } from 'node:timers/promises'
import {
  createPostgresCommitReplyBlackhole,
  createPostgresDisconnectBlackhole,
} from './helpers/realPostgresCancellation.js'

async function observed(check: () => boolean): Promise<void> {
  const deadline = Date.now() + 1_000
  while (!check()) {
    if (Date.now() >= deadline) throw new Error('proxy lifecycle observation did not arrive')
    await nextTurn()
  }
}

function query(sql: string): Buffer {
  const body = Buffer.from(`${sql}\0`)
  const header = Buffer.alloc(5)
  header[0] = 'Q'.charCodeAt(0)
  header.writeInt32BE(body.length + 4, 1)
  return Buffer.concat([header, body])
}

it('forwards fragmented COMMIT bytes, discards the reply and recovers later replies', async () => {
  const sockets = new Set<Socket>()
  let received = Buffer.alloc(0)
  let repliedToCommit = false
  const backend = createServer(socket => {
    sockets.add(socket)
    socket.on('data', chunk => {
      received = Buffer.concat([received, chunk])
      if (!repliedToCommit && received.length === 8 + query('COMMIT').length) {
        repliedToCommit = true
        socket.write('commit-reply')
      } else if (
        repliedToCommit &&
        received.length === 8 + query('COMMIT').length + query('SELECT 1').length
      ) {
        socket.write('later-reply')
      }
    })
    socket.on('end', () => socket.end())
    socket.on('error', () => {})
  })
  backend.listen(0, '127.0.0.1')
  await once(backend, 'listening')
  const address = backend.address()
  if (!address || typeof address === 'string') throw new Error('missing fixture backend address')
  const proxy = await createPostgresCommitReplyBlackhole(
    ['postgresql:', `//fixture@ignored/fixture?host=127.0.0.1&port=${address.port}`].join('')
  )
  const target = new URL(proxy.connectionString)
  expect(target.searchParams.has('port')).toBe(false)
  const client = createConnection({ host: target.hostname, port: Number(target.port) })
  const replies: Buffer[] = []
  client.on('data', chunk => replies.push(chunk))
  client.on('error', () => {})
  try {
    await once(client, 'connect')
    const startup = Buffer.alloc(8)
    startup.writeInt32BE(8, 0)
    startup.writeInt32BE(196608, 4)
    client.write(startup)
    await observed(() => received.length === 8)
    const commit = query('COMMIT')
    client.write(commit.subarray(0, 2))
    await observed(() => received.length === 10)
    expect(proxy.commands).toEqual([])
    client.write(commit.subarray(2))
    await proxy.commitForwarded
    await observed(() => proxy.discardedReplyBytes > 0)
    expect(received.subarray(8)).toEqual(commit)
    expect(proxy.commands).toEqual(['COMMIT'])
    expect(replies).toEqual([])
    proxy.allowReplies()
    client.write(query('SELECT 1'))
    await observed(() => Buffer.concat(replies).toString() === 'later-reply')
  } finally {
    client.destroy()
    await proxy.close()
    for (const socket of sockets) socket.destroy()
    await new Promise<void>((resolve, reject) =>
      backend.close(error => (error ? reject(error) : resolve()))
    )
  }
})

it('refuses an encrypted protocol prerequisite instead of pretending to observe COMMIT', async () => {
  await expect(
    createPostgresCommitReplyBlackhole(
      ['postgresql:', '//[email protected]/fixture?sslmode=require'].join('')
    )
  ).rejects.toThrow('plaintext PostgreSQL connection')
})

it('hides frontend Terminate and FIN as well as replies without closing the backend socket', async () => {
  const sockets = new Set<Socket>()
  let backendSocket: Socket | undefined
  let received = Buffer.alloc(0)
  let ended = false
  const backend = createServer({ allowHalfOpen: true }, socket => {
    backendSocket = socket
    sockets.add(socket)
    socket.on('data', chunk => {
      received = Buffer.concat([received, chunk])
      socket.write('visible-reply')
    })
    socket.on('end', () => {
      ended = true
    })
    socket.on('error', () => {})
  })
  backend.listen(0, '127.0.0.1')
  await once(backend, 'listening')
  const address = backend.address()
  if (!address || typeof address === 'string') throw new Error('missing fixture backend address')
  const proxy = await createPostgresDisconnectBlackhole(
    ['postgresql:', `//[email protected]:${address.port}/fixture`].join('')
  )
  const target = new URL(proxy.connectionString)
  const client = createConnection({ host: target.hostname, port: Number(target.port) })
  let replies = Buffer.alloc(0)
  client.on('data', chunk => {
    replies = Buffer.concat([replies, chunk])
  })
  client.on('error', () => {})
  try {
    await once(client, 'connect')
    const startup = Buffer.alloc(8)
    startup.writeInt32BE(8)
    startup.writeInt32BE(196608, 4)
    client.write(startup)
    await observed(() => replies.toString() === 'visible-reply')
    proxy.dropRepliesAndDisconnects()
    const terminate = Buffer.from([88, 0, 0, 0, 4])
    client.end(terminate)
    await observed(() => proxy.suppressedDisconnects === 1)
    expect(proxy.discardedFrontendBytes).toBe(terminate.length)
    expect(received).toEqual(startup)
    expect(ended).toBe(false)
    expect(backendSocket?.destroyed).toBe(false)
    backendSocket!.write('hidden-reply')
    await observed(() => proxy.discardedReplyBytes === Buffer.byteLength('hidden-reply'))
    expect(replies.toString()).toBe('visible-reply')
  } finally {
    client.destroy()
    await proxy.close()
    for (const socket of sockets) socket.destroy()
    await new Promise<void>((resolve, reject) =>
      backend.close(error => (error ? reject(error) : resolve()))
    )
  }
})