Skip to content

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

6.4 KB
Raw Blame
import { createServer } from 'node:http'
import { once } from 'node:events'
import type { AddressInfo } from 'node:net'
import WebSocket, { WebSocketServer } from 'ws'
import { forward, type ForwardRequest } from './forward'
import { handleUpgrade } from './upgrade'
import type { Ctx } from '../ctx'
import type { AppRow, EnvRow } from '../db'

function site() {
  const app = { id: 'app-one', name: 'one' } as AppRow
  const env = {
    id: 'env-one',
    app_id: app.id,
    name: 'main',
    active_box_id: 'box',
    live_deployment: 1,
    public_url: 'https://one.example.test',
    box_url: 'http://tunnel.example.test',
    forward_secret: 'gateway',
  } as EnvRow
  const resources = {
    boxStatus: jest.fn().mockResolvedValue('running'),
    wake: jest.fn(),
    wakeFailure: jest.fn(),
    recentlyWoken: jest.fn(),
    appUrl: () => env.public_url,
    currentSpec: async () => ({}),
    effectiveAccess: async () => 'public',
  }
  const ctx = {
    resources,
    store: { envById: async () => env, appById: async () => app },
    origins: { consoleUrl: () => 'https://dashboard.example.test' },
  } as unknown as Ctx
  const request = (options: Partial<ForwardRequest> = {}) =>
    forward(ctx, app, env, { path: '/hello', method: 'GET', headers: new Headers(), body: null, ...options })
  return { request, ctx, env, resources }
}

describe('App origin gateway', () => {
  afterEach(() => jest.restoreAllMocks())
  it('forwards the body, origin and application cookies and rewrites a redirect from the Box', async () => {
    const { request } = site()
    const headers = new Headers({
      location: 'http://tunnel.example.test/profile',
      'content-encoding': 'gzip',
      'x-app': 'hello',
    })
    for (const cookie of ['theme=dark; Path=/', 'bxl_session=internal', 'locale=en; Domain=example.test'])
      headers.append('set-cookie', cookie)
    const upstream = jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 303, headers }))
    const response = await request({
      method: 'POST',
      body: new Response('form-data').body,
      headers: new Headers({ cookie: 'bxl_session=private; theme=dark', 'x-forwarded-for': '192.0.2.1' }),
      clientIp: '192.0.2.2',
    })
    const options = upstream.mock.calls[0][1]!
    expect(await new Response(options.body).text()).toBe('form-data')
    const sent = new Headers(options.headers)
    expect(sent.get('cookie')).toBe('theme=dark')
    expect(sent.get('x-forwarded-for')).toBe('192.0.2.1, 192.0.2.2')
    expect(sent.get('x-forwarded-host')).toBe('one.example.test')
    expect(response.status).toBe(303)
    expect(response.headers.get('location')).toBe('https://one.example.test/profile')
    expect(response.headers.getSetCookie()).toEqual(['theme=dark; Path=/'])
    expect(response.headers.get('content-encoding')).toBeNull()
  })
  it.each(['json', 'html'])('renders unavailable, missing and sleeping App responses as %s', async (format) => {
    const { request, resources, env } = site()
    const headers = new Headers({ accept: format === 'html' ? 'text/html' : 'application/json' })
    async function check(status: number, code: string) {
      const res = await request({ headers })
      expect(res.status).toBe(status)
      if (format === 'html') expect(await res.text()).toContain('<h1>')
      else expect(await res.json()).toMatchObject({ error: { code } })
    }
    resources.boxStatus.mockResolvedValue('missing')
    await check(503, 'unavailable')
    resources.boxStatus.mockResolvedValue('stopped')
    await check(503, 'starting')
    expect(resources.wake).toHaveBeenCalledWith('box')
    resources.wakeFailure.mockReturnValue('failed to resume')
    await check(503, 'unavailable')
    env.live_deployment = null
    await check(503, 'not_deployed')
  })
  it('distinguishes wake-up responses, an App-provided 503, a gateway failure and a timeout', async () => {
    const { request, resources } = site()
    const upstream = jest.spyOn(globalThis, 'fetch')
    upstream.mockResolvedValueOnce(new Response('BOX_STOPPED', { status: 503 }))
    expect(await (await request()).json()).toMatchObject({ error: { code: 'starting' } })
    expect(resources.wake).toHaveBeenCalled()
    upstream.mockResolvedValueOnce(new Response('maintenance', { status: 503 }))
    expect(await (await request()).text()).toBe('maintenance')
    upstream.mockRejectedValueOnce(new Error('tunnel unavailable'))
    expect(await (await request()).json()).toMatchObject({ error: { code: 'bad_gateway' } })
    upstream.mockImplementationOnce(
      (_url, init) =>
        new Promise((_resolve, reject) => init!.signal!.addEventListener('abort', () => reject(new Error('deadline')))),
    )
    expect((await request({ timeoutMs: 5 })).status).toBe(504)
  })
  it('relays an upgraded connection and wakes a sleeping Box on reconnect', async () => {
    const { ctx, env, resources } = site()
    const upstream = createServer(),
      gateway = createServer()
    const echo = new WebSocketServer({ server: upstream })
    const headers = jest.fn()
    echo.on('connection', (ws, req) => {
      headers(req.url, req.headers)
      ws.on('message', (bytes) => ws.send(bytes))
    })
    gateway.on('upgrade', (req, socket, head) => void handleUpgrade(ctx, req, socket, head, env.id))
    upstream.listen(0, '127.0.0.1')
    gateway.listen(0, '127.0.0.1')
    await Promise.all([once(upstream, 'listening'), once(gateway, 'listening')])
    env.box_url = 'http://127.0.0.1:' + (upstream.address() as AddressInfo).port
    const url = 'ws://127.0.0.1:' + (gateway.address() as AddressInfo).port + '/socket?room=one'
    const client = new WebSocket(url, { headers: { cookie: 'bxl_session=app; theme=dark' } })
    try {
      await once(client, 'open')
      const received = once(client, 'message')
      client.send('hello')
      expect((await received)[0].toString()).toBe('hello')
      expect(headers).toHaveBeenCalledWith(
        '/socket?room=one',
        expect.objectContaining({ cookie: 'theme=dark', 'x-boxlite-gateway': 'gateway' }),
      )
      resources.boxStatus.mockResolvedValue('stopped')
      const sleeping = new WebSocket(url)
      expect((await once(sleeping, 'error'))[0].message).toContain('503')
      expect(resources.wake).toHaveBeenCalledWith(env.active_box_id)
    } finally {
      client.terminate()
      for (const ws of echo.clients) ws.terminate()
      echo.close()
      await Promise.all([upstream, gateway].map((s) => new Promise<void>((resolve) => s.close(() => resolve()))))
    }
  })
})