Skip to content

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

4.9 KB
Raw Blame
import type { AppRow, EnvRow } from './engine/db'
import { NotFoundException } from '@nestjs/common'
import { CloudAppResources } from './cloud-app-resources'
import { EncryptionService } from '../encryption/encryption.service'
import { BoxState } from '../box/enums/box-state.enum'

describe('hosted App platform resource adapters', () => {
  function platform() {
    const organization = { id: 'org' }
    const organizations = {
      findOne: jest.fn().mockResolvedValue(organization),
      assertOrganizationIsNotSuspended: jest.fn(),
    }
    const box = { id: 'box', name: 'demo', state: BoxState.STARTED }
    const boxes = {
      findOneByIdOrName: jest.fn().mockResolvedValue(box),
      toBoxDto: jest.fn().mockResolvedValue(box),
      getNetworkTunnelUrl: jest.fn().mockResolvedValue('https://tunnel.example.test'),
      start: jest.fn(),
      stop: jest.fn(),
      destroy: jest.fn(),
    }
    const tunnels = { prepare: jest.fn(), revoke: jest.fn() }
    const waiter = { waitForStarted: jest.fn() }
    const query = jest.fn()
    const encryption = new EncryptionService({ getOrThrow: (key) => 'test-' + key } as never)
    const service = new CloudAppResources(
      boxes as never,
      {} as never,
      tunnels as never,
      waiter as never,
      organizations as never,
      {} as never,
      { query } as never,
      encryption,
    )
    return {
      service,
      client: service.forOrganization('org'),
      boxes,
      tunnels,
      query,
      organizations,
      organization,
      waiter,
    }
  }

  test('rotates an unreadable tunnel token and uses the persisted credential when forwarding', async () => {
    const h = platform()
    h.query.mockResolvedValueOnce([]).mockResolvedValueOnce([])
    h.tunnels.prepare.mockResolvedValueOnce({ token: '***' }).mockResolvedValueOnce({ token: 'test-access-token' })
    const url = await h.client.tunnel('box', 8080)
    expect(h.tunnels.revoke).toHaveBeenCalledWith('box', 8080)
    expect(h.tunnels.prepare.mock.calls).toEqual([
      ['box', 8080, false],
      ['box', 8080, false],
    ])
    expect(h.query.mock.calls[0][1]).toEqual(['box', 'org'])
    const saved = h.query.mock.calls[1][1]
    expect(saved.slice(0, 3)).toEqual(['box', 'org', url])
    expect(saved[3]).not.toContain('test-access-token')
    h.query
      .mockResolvedValueOnce([{ url }])
      .mockResolvedValueOnce([{ encrypted_token: saved[3] }])
      .mockResolvedValueOnce([])
    expect(await h.client.tunnel('box', 8080)).toBe(url)
    expect(h.tunnels.prepare).toHaveBeenCalledTimes(2)
    expect(await h.service.tunnelHeaders(url)).toEqual({ 'X-BoxLite-Access-Token': 'test-access-token' })
    await expect(h.service.tunnelHeaders('missing')).rejects.toThrow(NotFoundException)
  })

  test('starts, observes, and cleans up Boxes within their organization, retaining tunnel rows on service errors', async () => {
    const h = platform()
    expect(await h.client.getBox('box')).toEqual({ id: 'box', name: 'demo', status: 'running' })
    h.boxes.findOneByIdOrName
      .mockRejectedValueOnce(new NotFoundException())
      .mockRejectedValueOnce(new Error('database offline'))
    expect(await h.client.getBox('gone')).toBeNull()
    await expect(h.client.getBox('box')).rejects.toThrow('database offline')
    await h.client.startBox('box')
    expect(h.boxes.start).toHaveBeenCalledWith('box', h.organization, expect.anything())
    expect(h.organizations.assertOrganizationIsNotSuspended).toHaveBeenCalledWith(h.organization)
    expect(h.waiter.waitForStarted).toHaveBeenCalledWith('box', 'org', 120)
    await h.client.stopBox('box')
    expect(h.boxes.stop).toHaveBeenCalledWith('box', 'org', expect.anything())
    h.boxes.destroy.mockRejectedValueOnce(new Error('still in use')).mockRejectedValueOnce(new NotFoundException())
    await expect(h.client.deleteBox('box')).rejects.toThrow('still in use')
    expect(h.query).not.toHaveBeenCalled()
    await h.client.deleteBox('gone')
    expect(h.query).toHaveBeenCalledWith(expect.stringContaining('DELETE'), ['gone', 'org'])
    h.organizations.findOne.mockResolvedValueOnce(null)
    await expect(h.client.startBox('box')).rejects.toThrow('Organization not found')
  })

  test('requires matching environment ownership before listing or creating a managed volume', async () => {
    const h = platform()
    const volumes = h.service.volumesForOrganization('org')
    const app = { id: 'app', org_id: 'org' } as AppRow
    const env = { id: 'env', app_id: 'app' } as EnvRow
    for (const [owner, target] of [
      [{ ...app, org_id: 'other' }, env],
      [app, { ...env, app_id: 'elsewhere' }],
    ] as const) {
      await expect(volumes.list(owner, target)).rejects.toThrow(NotFoundException)
      await expect(volumes.create(owner, target, 'data')).rejects.toThrow(NotFoundException)
    }
    expect(h.organizations.findOne).not.toHaveBeenCalled()
    h.organizations.findOne.mockResolvedValueOnce(null)
    await expect(volumes.create(app, env, 'data')).rejects.toThrow('Organization not found')
  })
})