Skip to content

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

30.6 KB
Raw Blame
/*
 * Copyright 2025 Daytona Platforms Inc.
 * Modified by BoxLite AI, 2025-2026
 * SPDX-License-Identifier: AGPL-3.0
 */

import { EventEmitter } from 'node:events'
import { ForbiddenException, HttpStatus, Logger, NotFoundException, RequestMethod } from '@nestjs/common'
import { HTTP_CODE_METADATA, METHOD_METADATA, PATH_METADATA, ROUTE_ARGS_METADATA } from '@nestjs/common/constants'
import { Reflector } from '@nestjs/core'
import { createProxyMiddleware } from 'http-proxy-middleware'
import { BoxliteProxyController } from './boxlite-proxy.controller'
import { hasNoEffect } from '../common/replay-no-effect'
import { Context } from '../common/context/context'
import { RequiredOrganizationResourcePermissions } from '../organization/decorators/required-organization-resource-permissions.decorator'
import { OrganizationResourcePermission } from '../organization/enums/organization-resource-permission.enum'
import { SystemRole } from '../user/enums/system-role.enum'

jest.mock('http-proxy-middleware', () => ({
  createProxyMiddleware: jest.fn(),
  fixRequestBody: jest.fn(),
}))
jest.mock('uuid', () => ({ v4: jest.fn(() => 'mock-uuid'), validate: jest.fn(() => true) }))

const activeAuth = {
  organizationId: 'org-1',
  organization: { id: 'org-1', suspended: false } as any,
}

function makeHarness() {
  const boxService = {
    findOneByIdOrName: jest.fn().mockResolvedValue({
      id: 'box-uuid',
      runnerId: 'runner-1',
      autoResume: true,
      state: 'started',
      inboundEnabled: true,
    }),
    updateLastActivityAt: jest.fn().mockResolvedValue(undefined),
    getNetworkTunnelUrl: jest.fn().mockResolvedValue('https://3000-box.proxy.test'),
  }
  const runnerService = {
    findOne: jest.fn().mockResolvedValue({ apiUrl: 'http://runner.local', apiKey: 'runner-key' }),
  }
  const autoResume = { ensureReady: jest.fn().mockResolvedValue(undefined) }
  const tunnelService = {
    prepare: jest.fn().mockResolvedValue({ isPublic: true, token: null }),
    revoke: jest.fn().mockResolvedValue(undefined),
  }
  const controller = new BoxliteProxyController(
    boxService as never,
    runnerService as never,
    autoResume as never,
    tunnelService as never,
  )
  return { controller, boxService, autoResume, tunnelService }
}

describe('BoxliteProxyController', () => {
  it('refuses stopped exec when auto-resume is disabled', async () => {
    const { controller, boxService, autoResume } = makeHarness()
    boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      runnerId: 'runner-1',
      autoResume: false,
      state: 'stopped',
      desiredState: 'stopped',
    } as never)
    jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)

    await expect(
      controller.proxyExec(
        activeAuth as never,
        'mybox',
        { method: 'POST' } as never,
        new EventEmitter() as never,
        jest.fn(),
      ),
    ).rejects.toMatchObject({ status: 409, message: expect.stringContaining('auto-resume is disabled') })
    expect(autoResume.ensureReady).not.toHaveBeenCalled()
    expect(createProxyMiddleware).not.toHaveBeenCalled()
  })

  it('passes the private choice and returns only the URI and access descriptor', async () => {
    const { controller, tunnelService } = makeHarness()
    tunnelService.prepare.mockResolvedValue({ isPublic: false, token: 'blt_first-secret' })
    await expect(
      controller.proxyNetworkTunnel(activeAuth as never, 'mybox', 3000, Context.user(), { isPublic: false }),
    ).resolves.toEqual({ uri: 'https://3000-box.proxy.test', isPublic: false, token: 'blt_first-secret' })
    expect(tunnelService.prepare).toHaveBeenCalledWith('box-uuid', 3000, false)
  })
  beforeEach(() => jest.clearAllMocks())
  afterEach(() => jest.useRealTimers())

  it('requires box write permission to declare a public port', () => {
    const reflector = new Reflector()
    expect(
      reflector.get(RequiredOrganizationResourcePermissions, BoxliteProxyController.prototype.proxyNetworkTunnel),
    ).toEqual([OrganizationResourcePermission.WRITE_BOXES])
  })

  it('revokes a public port with DELETE, answering 204, under box write permission', () => {
    const reflector = new Reflector()
    const handler = BoxliteProxyController.prototype.revokeNetworkTunnel

    expect(Reflect.getMetadata(METHOD_METADATA, handler)).toBe(RequestMethod.DELETE)
    expect(Reflect.getMetadata(PATH_METADATA, handler)).toBe(':boxId/network/tunnel')
    expect(Reflect.getMetadata(HTTP_CODE_METADATA, handler)).toBe(HttpStatus.NO_CONTENT)
    expect(reflector.get(RequiredOrganizationResourcePermissions, handler)).toEqual([
      OrganizationResourcePermission.WRITE_BOXES,
    ])
  })

  it('revokes the port of the box the caller names, whatever its inbound mode or state', async () => {
    const { controller, boxService, tunnelService } = makeHarness()
    boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      runnerId: 'runner-1',
      autoResume: false,
      state: 'stopped',
      inboundEnabled: false,
    })

    await controller.revokeNetworkTunnel(activeAuth as never, 'public-box', 3000)

    expect(boxService.findOneByIdOrName).toHaveBeenCalledWith('public-box', 'org-1')
    expect(tunnelService.revoke).toHaveBeenCalledWith('box-uuid', 3000)
  })

  it('does not revoke anything for a box outside the organization', async () => {
    const { controller, boxService, tunnelService } = makeHarness()
    boxService.findOneByIdOrName.mockRejectedValue(new NotFoundException('Box public-box not found'))

    await expect(controller.revokeNetworkTunnel(activeAuth as never, 'public-box', 3000)).rejects.toMatchObject({
      status: 404,
    })
    expect(tunnelService.revoke).not.toHaveBeenCalled()
  })

  it('rewrites public box ids to internal box ids before proxying exec', async () => {
    const proxyHandler = jest.fn()
    jest.mocked(createProxyMiddleware).mockReturnValue(proxyHandler as never)
    const { controller, boxService } = makeHarness()
    const req = { url: '/api/v1/boxes/public-box/exec', method: 'POST' }
    const res = new EventEmitter()
    const next = jest.fn()

    await controller.proxyExec(activeAuth as never, 'public-box', req as never, res as never, next)

    const proxyOptions = jest.mocked(createProxyMiddleware).mock.calls[0][0]
    const pathRewrite = proxyOptions.pathRewrite as (path: string, req: unknown) => string
    expect(pathRewrite('/api/v1/boxes/public-box/exec', req)).toBe('/v1/boxes/box-uuid/exec')
    expect(boxService.findOneByIdOrName).toHaveBeenCalledWith('public-box', 'org-1')
    expect(proxyHandler).toHaveBeenCalledWith(req, res, next)
  })

  it('marks an admission refusal before auto-resume and dispatch as no-effect', async () => {
    jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
    const { controller, boxService, autoResume } = makeHarness()
    boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      runnerId: 'runner-1',
      autoResume: false,
      state: 'stopped',
      desiredState: 'stopped',
    })
    const error = await controller
      .proxyExec(activeAuth as never, 'public-box', { method: 'POST' } as never, new EventEmitter() as never, jest.fn())
      .catch((error: unknown) => error)
    expect(error).toMatchObject({ status: 409 })
    expect(hasNoEffect(error)).toBe(true)
    expect(autoResume.ensureReady).not.toHaveBeenCalled()
    expect(createProxyMiddleware).not.toHaveBeenCalled()
  })
  it('lists a stopped box without resuming it or extending its idle lifetime', async () => {
    jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
    const { controller, boxService, autoResume } = makeHarness()
    boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      runnerId: 'runner-1',
      autoResume: true,
      state: 'stopped',
      autoStop: 10,
    })

    await controller.proxyExecList(activeAuth as never, 'public-box', {} as never, {} as never, jest.fn())

    expect(boxService.updateLastActivityAt).not.toHaveBeenCalled()
    expect(autoResume.ensureReady).not.toHaveBeenCalled()
    const proxyOptions = jest.mocked(createProxyMiddleware).mock.calls[0][0]
    const pathRewrite = proxyOptions.pathRewrite as (path: string, req: unknown) => string
    expect(pathRewrite('/api/v1/boxes/public-box/executions', {})).toBe('/v1/boxes/box-uuid/executions')
  })

  it('does not expose execution inventory outside the caller organization', async () => {
    const { controller, boxService } = makeHarness()
    boxService.findOneByIdOrName.mockRejectedValue(new NotFoundException('Box public-box not found'))

    await expect(
      controller.proxyExecList(activeAuth as never, 'public-box', {} as never, {} as never, jest.fn()),
    ).rejects.toMatchObject({ status: 404 })

    expect(boxService.findOneByIdOrName).toHaveBeenCalledWith('public-box', 'org-1')
    expect(createProxyMiddleware).not.toHaveBeenCalled()
  })

  it('disables the runner timeout for files only', async () => {
    jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
    const { controller } = makeHarness()

    await controller.proxyFiles(activeAuth as never, 'public-box', { url: '/files' } as never, {} as never, jest.fn())
    await controller.proxyExec(activeAuth as never, 'public-box', { url: '/exec' } as never, {} as never, jest.fn())

    const fileOptions = jest.mocked(createProxyMiddleware).mock.calls[0][0]
    const execOptions = jest.mocked(createProxyMiddleware).mock.calls[1][0]
    expect(fileOptions.proxyTimeout).toBe(0)
    expect(execOptions.proxyTimeout).toBe(300000)
  })

  it('returns the public endpoint for JSON tunnel requests', async () => {
    const { controller, boxService, tunnelService } = makeHarness()

    const result = await controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, Context.user())

    expect(boxService.getNetworkTunnelUrl).toHaveBeenCalledWith('public-box', 'org-1', 3000)
    expect(tunnelService.prepare).toHaveBeenCalledWith('box-uuid', 3000, true)
    expect(boxService.getNetworkTunnelUrl.mock.invocationCallOrder[0]).toBeLessThan(
      tunnelService.prepare.mock.invocationCallOrder[0],
    )
    expect(result).toEqual({ uri: 'https://3000-box.proxy.test', isPublic: true, token: null })
  })

  it('does not return a tunnel URI when the declaration cannot be saved', async () => {
    const { controller, boxService, tunnelService } = makeHarness()
    tunnelService.prepare.mockRejectedValue(new Error('database unavailable'))

    await expect(
      controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, Context.user()),
    ).rejects.toThrow('database unavailable')
    expect(boxService.getNetworkTunnelUrl).toHaveBeenCalledWith('public-box', 'org-1', 3000)
  })

  it('does not declare a public port when tunnel URL resolution fails', async () => {
    const { controller, boxService, tunnelService } = makeHarness()
    boxService.getNetworkTunnelUrl.mockRejectedValue(new Error('region unavailable'))

    await expect(
      controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, Context.user()),
    ).rejects.toThrow('region unavailable')
    expect(tunnelService.prepare).not.toHaveBeenCalled()
  })

  it('rejects a tunnel request for a box with inbound access disabled with 409', async () => {
    const { controller, boxService } = makeHarness()
    boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      runnerId: 'runner-1',
      autoResume: true,
      state: 'started',
      inboundEnabled: false,
    })

    await expect(
      controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, Context.user()),
    ).rejects.toMatchObject({
      status: 409,
    })
    expect(boxService.getNetworkTunnelUrl).not.toHaveBeenCalled()
  })

  it('rejects a tunnel request for a stopped, non-autoResume box with 409', async () => {
    const { controller, boxService, autoResume } = makeHarness()
    boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      runnerId: 'runner-1',
      autoResume: false,
      state: 'stopped',
      inboundEnabled: true,
    })

    await expect(
      controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, Context.user()),
    ).rejects.toMatchObject({
      status: 409,
      // Pin the reason: without inboundEnabled: true this 409s at the visibility
      // gate instead, and the state policy under test never runs.
      message: expect.stringContaining('is not running'),
    })
    expect(autoResume.ensureReady).not.toHaveBeenCalled()
    expect(boxService.getNetworkTunnelUrl).not.toHaveBeenCalled()
  })

  it('hands a stopped autoResume box its tunnel URI without waking it', async () => {
    // The CONNECT on that URI wakes the box through the proxy; waking it here
    // too would only hold the caller for a start the proxy already covers.
    const { controller, boxService, autoResume, tunnelService } = makeHarness()
    boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      runnerId: 'runner-1',
      autoResume: true,
      state: 'stopped',
      inboundEnabled: true,
    })

    const result = await controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, Context.user())

    expect(autoResume.ensureReady).not.toHaveBeenCalled()
    expect(tunnelService.prepare).toHaveBeenCalledWith('box-uuid', 3000, true)
    expect(result).toEqual({ uri: 'https://3000-box.proxy.test', isPublic: true, token: null })
  })

  it('counts a tunnel request as activity so AutoStop does not reap the box', async () => {
    // POL-326: without this the box we just handed out stays
    // eligible for the idle sweeper, so the caller's tunnel dies under it.
    const { controller, boxService } = makeHarness()

    await controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, Context.user())

    expect(boxService.updateLastActivityAt).toHaveBeenCalledWith('box-uuid', expect.any(Date))
  })

  it('does not record activity for a box it refuses to expose', async () => {
    const { controller, boxService } = makeHarness()
    boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      runnerId: 'runner-1',
      autoResume: true,
      state: 'started',
      inboundEnabled: false,
    })

    await expect(
      controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, Context.user()),
    ).rejects.toMatchObject({ status: 409 })
    expect(boxService.updateLastActivityAt).not.toHaveBeenCalled()
  })

  it.each(['error', 'archived', 'archiving', 'destroying', 'resizing', 'unknown'])(
    'rejects state %s with 409, even with autoResume',
    async (state) => {
      // The proxy's wake cannot bring these to STARTED, so their URI could
      // only ever fail.
      const { controller, boxService, autoResume } = makeHarness()
      boxService.findOneByIdOrName.mockResolvedValue({
        id: 'box-uuid',
        runnerId: 'runner-1',
        autoResume: true,
        state,
        inboundEnabled: true,
      })

      await expect(
        controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, Context.user()),
      ).rejects.toMatchObject({ status: 409 })
      expect(autoResume.ensureReady).not.toHaveBeenCalled()
      expect(boxService.getNetworkTunnelUrl).not.toHaveBeenCalled()
    },
  )

  it.each(['stopping', 'starting', 'creating', 'restoring'])(
    'hands out the URI without waking an autoResume box in state %s',
    async (state) => {
      const { controller, boxService, autoResume } = makeHarness()
      boxService.findOneByIdOrName.mockResolvedValue({
        id: 'box-uuid',
        runnerId: 'runner-1',
        autoResume: true,
        state,
        inboundEnabled: true,
      })

      await controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, Context.user())

      expect(autoResume.ensureReady).not.toHaveBeenCalled()
      expect(boxService.getNetworkTunnelUrl).toHaveBeenCalled()
    },
  )

  it.each(['creating', 'starting', 'error', 'archived', 'unknown'])(
    'rejects a tunnel request for a non-started box in state %s',
    async (state) => {
      const { controller, boxService } = makeHarness()
      boxService.findOneByIdOrName.mockResolvedValue({
        id: 'box-uuid',
        runnerId: 'runner-1',
        autoResume: false,
        state,
        inboundEnabled: true,
      })

      await expect(
        controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, Context.user()),
      ).rejects.toMatchObject({
        status: 409,
        message: expect.stringContaining('is not running'),
      })
      expect(boxService.getNetworkTunnelUrl).not.toHaveBeenCalled()
    },
  )

  it('auto-resumes exec and files but treats metrics as observation-only', async () => {
    jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
    const { controller, boxService, autoResume } = makeHarness()

    await controller.proxyExec(activeAuth as never, 'public-box', { url: '/exec' } as never, {} as never, jest.fn())
    await controller.proxyFiles(activeAuth as never, 'public-box', { url: '/files' } as never, {} as never, jest.fn())
    expect(autoResume.ensureReady).toHaveBeenCalledTimes(2)
    expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(2)

    autoResume.ensureReady.mockClear()
    boxService.updateLastActivityAt.mockClear()
    await controller.proxyMetrics(
      activeAuth as never,
      'public-box',
      { url: '/metrics' } as never,
      {} as never,
      jest.fn(),
    )
    expect(autoResume.ensureReady).not.toHaveBeenCalled()
    expect(boxService.updateLastActivityAt).not.toHaveBeenCalled()
  })

  it('does not proxy when the strict AutoResume gate fails', async () => {
    const proxyHandler = jest.fn()
    jest.mocked(createProxyMiddleware).mockReturnValue(proxyHandler as never)
    const { controller, autoResume } = makeHarness()
    autoResume.ensureReady.mockRejectedValue(new Error('start failed'))

    const error = await controller
      .proxyExec(activeAuth as never, 'public-box', { url: '/exec' } as never, {} as never, jest.fn())
      .catch((error: unknown) => error)
    expect(error).toMatchObject({ message: 'start failed' })
    expect(hasNoEffect(error)).toBe(false)
    expect(proxyHandler).not.toHaveBeenCalled()
  })

  it('does not auto-resume a box whose autoResume switch is off', async () => {
    jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
    const { controller, boxService, autoResume } = makeHarness()
    boxService.findOneByIdOrName.mockResolvedValue({ id: 'box-uuid', runnerId: 'runner-1', autoResume: false })

    await controller.proxyExec(activeAuth as never, 'public-box', { url: '/exec' } as never, {} as never, jest.fn())

    expect(autoResume.ensureReady).not.toHaveBeenCalled()
  })

  it('surfaces suspended-organization failures and never proxies', async () => {
    const proxyHandler = jest.fn()
    jest.mocked(createProxyMiddleware).mockReturnValue(proxyHandler as never)
    const { controller, autoResume } = makeHarness()
    autoResume.ensureReady.mockRejectedValue(new ForbiddenException('Organization is suspended'))

    await expect(
      controller.proxyExec(activeAuth as never, 'public-box', { url: '/exec' } as never, {} as never, jest.fn()),
    ).rejects.toThrow(ForbiddenException)
    expect(proxyHandler).not.toHaveBeenCalled()
  })

  it('refreshes activity for the whole lifetime of a file transfer', async () => {
    jest.useFakeTimers()
    jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
    const { controller, boxService } = makeHarness()
    boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      runnerId: 'runner-1',
      autoResume: true,
      autoStop: 900,
    })
    const res = new EventEmitter()

    await controller.proxyFiles(activeAuth as never, 'public-box', { url: '/files' } as never, res as never, jest.fn())

    expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(1)

    jest.advanceTimersByTime(450_000)
    expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(2)

    res.emit('close')
  })

  it('keeps the heartbeat below half the autoStop window for a one-second setting', async () => {
    jest.useFakeTimers()
    jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
    const { controller, boxService } = makeHarness()
    boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      runnerId: 'runner-1',
      autoResume: true,
      autoStop: 1,
    })
    const res = new EventEmitter()

    await controller.proxyFiles(activeAuth as never, 'public-box', { url: '/files' } as never, res as never, jest.fn())
    expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(1)

    // autoStop=1 → the heartbeat must fire within the window, not at its end.
    jest.advanceTimersByTime(500)
    expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(2)

    res.emit('close')
  })

  it('stops refreshing activity once the transfer completes', async () => {
    jest.useFakeTimers()
    jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
    const { controller, boxService } = makeHarness()
    boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      runnerId: 'runner-1',
      autoResume: true,
      autoStop: 900,
    })
    const res = new EventEmitter()

    await controller.proxyFiles(activeAuth as never, 'public-box', { url: '/files' } as never, res as never, jest.fn())
    expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(1)

    res.emit('close')
    jest.advanceTimersByTime(900_000)
    expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(1)
  })
})

describe('BoxliteProxyController business events', () => {
  // Every business event [message, attributes] logged, in order.
  let events: [string, Record<string, string>][]
  const caller = { userId: 'user-1', role: 'user', email: '[email protected]', apiKey: {}, organizationId: 'org-1' }

  function harness() {
    jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
    const built = makeHarness()
    built.boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      organizationId: 'org-1',
      runnerId: 'runner-1',
      autoResume: false,
      state: 'started',
      desiredState: 'started',
      inboundEnabled: true,
    })
    return built
  }

  const request = (method: string, url: string) => ({ method, url, user: caller, get: () => undefined }) as never
  const response = () => Object.assign(new EventEmitter(), { statusCode: 200 })

  function tunnelRequestContext(req: unknown): Context {
    const parameters: Record<string, { index: number; factory?: (data: unknown, execution: unknown) => Context }> =
      Reflect.getMetadata(ROUTE_ARGS_METADATA, BoxliteProxyController, 'proxyNetworkTunnel')
    const parameter = Object.values(parameters).find(({ index, factory }) => index === 3 && factory)
    if (!parameter?.factory) throw new Error('Tunnel context decorator is missing')
    return parameter.factory(undefined, { switchToHttp: () => ({ getRequest: () => req }) })
  }

  beforeEach(() => {
    jest.clearAllMocks()
    events = []
    const record = (message: string, attributes: Record<string, string>) => {
      if (/^(box|tunnel)\./.test(message)) events.push([message, attributes])
    }
    jest.spyOn(Logger.prototype, 'log').mockImplementation(record as never)
    jest.spyOn(Logger.prototype, 'error').mockImplementation(record as never)
  })

  afterEach(() => jest.restoreAllMocks())

  it('records an exec as requested by the caller, then success when the response completes', async () => {
    const { controller } = harness()
    const res = response()

    await controller.proxyExec(activeAuth as never, 'public-box', request('POST', '/exec'), res as never, jest.fn())
    expect(events.map(([message]) => message)).toEqual(['box.exec requested'])

    res.emit('finish')
    res.emit('close')

    expect(events.map(([message]) => message)).toEqual(['box.exec requested', 'box.exec success'])
    for (const [, attributes] of events) {
      expect(attributes).toEqual(
        expect.objectContaining({
          'correlation.id': 'box-uuid',
          'organization.id': 'org-1',
          'actor.kind': 'user',
          'user.id': 'user-1',
          'auth.method': 'api_key',
        }),
      )
    }
  })

  it('records an error status as the exception', async () => {
    const { controller } = harness()
    const res = response()

    await controller.proxyExec(activeAuth as never, 'public-box', request('POST', '/exec'), res as never, jest.fn())
    res.statusCode = 502
    res.emit('finish')

    expect(events[1]).toEqual(['box.exec exception', expect.objectContaining({ 'exception.type': 'http_502' })])
  })

  it.each(
    [SystemRole.ADMIN, SystemRole.USER].flatMap((role) =>
      ['exec', 'file_upload'].flatMap((operation) =>
        [200, 502].flatMap((status) =>
          ['jwt', 'api_key'].map((authMethod) => [role, operation, status, authMethod] as const),
        ),
      ),
    ),
  )('preserves %s identity for proxied %s status %s with %s', async (role, operation, status, authMethod) => {
    const { controller } = harness()
    const userId = role === SystemRole.ADMIN ? 'admin-1' : 'user-1'
    const auth = { ...activeAuth, ...caller, userId, role, apiKey: authMethod === 'api_key' ? {} : undefined }
    const req = { method: operation === 'exec' ? 'POST' : 'PUT', url: '/operation', user: auth, get: () => undefined }
    const res = response()
    if (operation === 'exec') {
      await controller.proxyExec(auth as never, 'public-box', req as never, res as never, jest.fn())
    } else {
      await controller.proxyFiles(auth as never, 'public-box', req as never, res as never, jest.fn())
    }
    res.statusCode = status
    res.emit('finish')
    res.emit('close')
    expect(events.map(([message]) => message)).toEqual([
      `box.${operation} requested`,
      `box.${operation} ${status < 400 ? 'success' : 'exception'}`,
    ])
    if (status >= 400) expect(events[1][1]['exception.type']).toBe(`http_${status}`)
    for (const [, attributes] of events) {
      expect(attributes).toEqual(
        expect.objectContaining({
          'actor.kind': role,
          'user.id': userId,
          'auth.method': authMethod,
          'organization.id': 'org-1',
          'correlation.id': 'box-uuid',
        }),
      )
    }
  })

  it.each(['closed', 'finished'])('accounts for a response already %s during the box lookup', async (state) => {
    const { controller, boxService } = harness()
    const box = await boxService.findOneByIdOrName()
    let release!: (value: typeof box) => void
    boxService.findOneByIdOrName.mockReturnValue(
      new Promise((resolve) => {
        release = resolve
      }),
    )
    const res = Object.assign(response(), { destroyed: false, writableFinished: false })
    const pending = controller.proxyExec(
      activeAuth as never,
      'public-box',
      request('POST', '/exec'),
      res as never,
      jest.fn(),
    )
    if (state === 'finished') {
      res.writableFinished = true
      res.emit('finish')
    }
    res.destroyed = true
    res.emit('close')
    release(box)
    await pending
    expect(events.map(([message]) => message)).toEqual([
      'box.exec requested',
      state === 'finished' ? 'box.exec success' : 'box.exec exception',
    ])
    if (state === 'closed') expect(events[1][1]['exception.type']).toBe('client_closed')
    res.emit('finish')
    res.emit('close')
    expect(events).toHaveLength(2)
  })

  it('records a client that disconnects before the response completes as client_closed, once', async () => {
    const { controller } = harness()
    const res = response()

    await controller.proxyFiles(activeAuth as never, 'public-box', request('PUT', '/files'), res as never, jest.fn())
    res.emit('close')
    res.emit('finish')

    expect(events).toEqual([
      ['box.file_upload requested', expect.anything()],
      ['box.file_upload exception', expect.objectContaining({ 'exception.type': 'client_closed' })],
    ])
  })

  it('records nothing for reads: downloads and other exec calls', async () => {
    const { controller } = harness()

    await controller.proxyFiles(
      activeAuth as never,
      'public-box',
      request('GET', '/files'),
      response() as never,
      jest.fn(),
    )
    await controller.proxyExec(
      activeAuth as never,
      'public-box',
      request('GET', '/exec'),
      response() as never,
      jest.fn(),
    )

    expect(events).toEqual([])
  })

  it('records a tunnel as requested, then success with its organization', async () => {
    const { controller } = harness()
    const ctx = Context.user({ userId: 'user-1', authMethod: 'jwt' })

    await controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, ctx)

    expect(events.map(([message]) => message)).toEqual(['tunnel.create requested', 'tunnel.create success'])
    expect(events[1][1]).toEqual(
      expect.objectContaining({ 'correlation.id': 'box-uuid', 'organization.id': 'org-1', 'user.id': 'user-1' }),
    )
  })

  it('records a refused tunnel as a conflict', async () => {
    const { controller, boxService } = harness()
    boxService.findOneByIdOrName.mockResolvedValue({
      id: 'box-uuid',
      organizationId: 'org-1',
      runnerId: 'runner-1',
      autoResume: false,
      state: 'started',
      desiredState: 'started',
      inboundEnabled: false,
    })

    await expect(
      controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000, Context.user()),
    ).rejects.toThrow()

    expect(events[1]).toEqual(['tunnel.create exception', expect.objectContaining({ 'exception.type': 'conflict' })])
  })

  it.each(
    [SystemRole.ADMIN, SystemRole.USER].flatMap((role) =>
      ['jwt', 'api_key'].flatMap((method) => [true, false].map((allowed) => [role, method, allowed] as const)),
    ),
  )('preserves decorated %s tunnel attribution with %s, allowed=%s', async (role, method, allowed) => {
    const { controller, boxService } = harness()
    const box = await boxService.findOneByIdOrName()
    boxService.findOneByIdOrName.mockResolvedValue({ ...box, inboundEnabled: allowed })
    const auth = { ...activeAuth, ...caller, role, apiKey: method === 'api_key' ? {} : undefined }
    const req = {
      user: auth,
      get: (name: string) => (name.toLowerCase() === 'x-boxlite-source' ? 'dashboard' : undefined),
    }
    const ctx = tunnelRequestContext(req)
    const result = controller.proxyNetworkTunnel(auth as never, 'public-box', 3000, ctx)
    if (allowed) await result
    else await expect(result).rejects.toThrow()
    expect(events.map(([message]) => message)).toEqual([
      'tunnel.create requested',
      `tunnel.create ${allowed ? 'success' : 'exception'}`,
    ])
    for (const [, attributes] of events) {
      expect(attributes).toMatchObject({
        'actor.kind': role,
        'user.id': caller.userId,
        'auth.method': method,
        'client.source': 'dashboard',
        'organization.id': 'org-1',
        'correlation.id': 'box-uuid',
      })
    }
  })
})