Skip to content

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

7.9 KB
Raw Blame
/*
 * Copyright 2025 BoxLite AI
 * SPDX-License-Identifier: AGPL-3.0
 */

import { BoxState } from '../../box/enums/box-state.enum'
import { Box } from '../../box/entities/box.entity'
import { BoxDto } from '../../box/dto/box.dto'
import { boxToBoxResponse, createBoxToCreateBox } from './box-to-box.mapper'

describe('BoxLite lifecycle policy mapper', () => {
  it.each([
    ['enabled', true],
    ['disabled', false],
  ] as const)('maps inbound.mode=%s to inbound enabled %s', (mode, expected) => {
    const mapped = createBoxToCreateBox({
      network: {
        outbound: { mode: 'enabled' },
        inbound: { mode },
      },
    })

    expect(mapped.inboundEnabled).toBe(expected)
  })

  it('leaves inbound disabled and outbound to the organization default without a network spec', () => {
    const mapped = createBoxToCreateBox({})

    expect([mapped.inboundEnabled, mapped.outboundEnabled, mapped.outboundAllowNet]).toEqual([
      false,
      undefined,
      undefined,
    ])
  })

  it.each([
    ['enabled', [' api.openai.com ', '', '10.0.0.0/8'], true, ['api.openai.com', '10.0.0.0/8']],
    ['enabled', [], true, undefined],
    ['disabled', [], false, undefined],
    ['disabled', ['api.openai.com'], false, ['api.openai.com']],
  ] as const)(
    'maps outbound %s with allow_net %j to enabled %s and entries %j',
    (mode, allowNet, expectedEnabled, expected) => {
      const mapped = createBoxToCreateBox({ network: { outbound: { mode, allow_net: [...allowNet] } } })

      expect(mapped.outboundEnabled).toBe(expectedEnabled)
      expect(mapped.outboundAllowNet).toEqual(expected)
    },
  )

  it('maps second-based create fields into the control-plane DTO', () => {
    const mapped = createBoxToCreateBox({
      auto_stop: 1800,
      auto_delete: 604800,
      auto_resume: false,
    })

    expect(mapped.autoStop).toBe(1800)
    expect(mapped.autoDelete).toBe(604800)
    expect(mapped.autoResume).toBe(false)
  })

  it('maps REST volume specs to managed volume mounts', () => {
    const mapped = createBoxToCreateBox({
      volumes: [{ managed_volume: 'volume-123', guest_path: '/data', read_only: false }],
    })

    expect(mapped.volumes).toEqual([{ volumeId: 'volume-123', mountPath: '/data' }])
  })

  // A name is as valid as an id here; VolumeService.validateVolumes resolves
  // either, so the mapper must pass the value through untouched.
  it('passes a volume name through as-is', () => {
    const mapped = createBoxToCreateBox({
      volumes: [{ managed_volume: 'customer-data', guest_path: '/data', read_only: false }],
    })

    expect(mapped.volumes).toEqual([{ volumeId: 'customer-data', mountPath: '/data' }])
  })

  it('maps REST secret specs to secret placeholder rules', () => {
    const mapped = createBoxToCreateBox({
      secrets: [
        {
          name: 'openai',
          value: 'sk-test',
          hosts: ['api.openai.com'],
          placeholder: '<BOXLITE_SECRET:openai>',
          headers: { 'x-api-key': '{value}' },
        } as any,
      ],
    })

    expect(mapped.secrets).toEqual([
      {
        name: 'openai',
        value: 'sk-test',
        hosts: ['api.openai.com'],
        placeholder: '<BOXLITE_SECRET:openai>',
        headers: { 'x-api-key': '{value}' },
      },
    ])
  })

  it('passes a secret without a placeholder through untouched', () => {
    const mapped = createBoxToCreateBox({
      secrets: [
        { name: 'openai', value: 'sk-test', hosts: ['api.openai.com'], headers: { Authorization: 'Bearer {value}' } },
      ],
    })

    expect(mapped.secrets).toEqual([
      { name: 'openai', value: 'sk-test', hosts: ['api.openai.com'], headers: { Authorization: 'Bearer {value}' } },
    ])
  })

  it('returns the effective second-based policy', () => {
    const response = boxToBoxResponse({
      id: 'box-1',
      name: 'demo',
      state: BoxState.STARTED,
      labels: {},
      autoStop: 1800,
      autoDelete: 604800,
      autoResume: false,
    } as any)

    expect(response.auto_stop).toBe(1800)
    expect(response.auto_delete).toBe(604800)
    expect(response.auto_resume).toBe(false)
  })

  it('defaults auto_resume to true when missing', () => {
    const response = boxToBoxResponse({
      id: 'box-1',
      name: 'demo',
      state: BoxState.STARTED,
      labels: {},
    } as any)

    expect(response.auto_resume).toBe(true)
  })
})

// These four validated, were audit-logged, and were then dropped on the floor
// here: the mapper simply never read them, so a caller got a 201 and a box that
// ignored the working directory, entrypoint, command and user they asked for.
describe('BoxLite container process options mapper', () => {
  it.each([false, true])('reports persisted guest privilege %s', (privileged) => {
    const row = new Box('us', 'guest-policy')
    row.id = 'box-1'
    row.privileged = privileged

    const response = boxToBoxResponse(BoxDto.fromBox(row))

    expect(response).toEqual(expect.objectContaining({ privileged }))
  })

  it('forwards guest privileged and preserves its default', () => {
    expect(createBoxToCreateBox({ advanced: { privileged: true } }).privileged).toBe(true)
    expect(createBoxToCreateBox({}).privileged).toBe(false)
  })
  it('carries the container process options into the control-plane DTO', () => {
    const mapped = createBoxToCreateBox({
      working_dir: '/app',
      entrypoint: ['python'],
      cmd: ['-c', 'print(1)'],
      user: '1000:1000',
    })

    expect(mapped.workingDir).toBe('/app')
    expect(mapped.entrypoint).toEqual(['python'])
    expect(mapped.cmd).toEqual(['-c', 'print(1)'])
    expect(mapped.runAsUser).toBe('1000:1000')
  })

  // `user` feeds two fields with different jobs. runAsUser is the real OCI
  // process.user override; osUser is the Daytona-era warm-pool label, and
  // box.service.ts still defaults it to 'boxlite' when absent.
  it('feeds user to both the process override and the warm-pool label', () => {
    const mapped = createBoxToCreateBox({ user: 'node' })

    expect(mapped.runAsUser).toBe('node')
    expect(mapped.user).toBe('node')
  })

  // The load-bearing case: an unset user must stay unset, so box.service.ts
  // does not hand every box a USER override its image may never define.
  it('leaves runAsUser undefined when the caller asks for no user', () => {
    const mapped = createBoxToCreateBox({ image: 'alpine:latest' })

    expect(mapped.runAsUser).toBeUndefined()
    expect(mapped.workingDir).toBeUndefined()
    expect(mapped.entrypoint).toBeUndefined()
    expect(mapped.cmd).toBeUndefined()
  })

  // Exit code 0 is what separates a command that succeeded from one that did
  // not, so the mapper has to publish it rather than drop it the way a falsy
  // check would.
  it.each([
    ['a main command ended by a signal', 137, 137],
    ['a main command that succeeded', 0, 0],
  ])('reports the exit code of %s', (_case, read, expected) => {
    const response = boxToBoxResponse({
      id: 'box-1',
      state: BoxState.STOPPED,
      labels: {},
      exitCode: read,
    } as any)

    expect(response.exit_code).toBe(expected)
  })

  // The `/v1` read carries the control-plane policy unchanged, from the box
  // row through `BoxDto` to the response.
  it('reports the network policy of the box row', () => {
    const row = new Box('us', 'net')
    row.id = 'box-1'
    row.inboundEnabled = true
    row.outboundEnabled = true
    row.outboundAllowNet = ['api.openai.com']

    const response = boxToBoxResponse(BoxDto.fromBox(row))

    expect(response.network).toEqual({
      outbound: { mode: 'enabled', allow_net: ['api.openai.com'] },
      inbound: { mode: 'enabled', allow_net: [] },
    })
  })

  it('omits exit_code when the box has none', () => {
    const response = boxToBoxResponse({
      id: 'box-1',
      state: BoxState.STARTED,
      labels: {},
      exitCode: undefined,
    } as any)

    expect(response.exit_code).toBeUndefined()
    expect(JSON.parse(JSON.stringify(response))).not.toHaveProperty('exit_code')
  })
})