Skip to content

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

5.2 KB
Raw Blame
/*
 * Copyright 2026 BoxLite AI
 * SPDX-License-Identifier: AGPL-3.0
 */

import { Controller, Get, INestApplication } from '@nestjs/common'
import { ApiTags, OpenAPIObject, SwaggerModule } from '@nestjs/swagger'
import { Test } from '@nestjs/testing'
import Ajv from 'ajv'
import { readFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { parse } from 'yaml'
import { getOpenApiConfig } from './openapi.config'
import { setupPlatformSwagger } from './platform-swagger'

@ApiTags('box')
@Controller('box')
class BoxController {
  @Get('paginated')
  boxes() {
    return []
  }
}

@ApiTags('volumes')
@Controller('volumes')
class VolumeController {
  @Get()
  volumes() {
    return []
  }
}

const specDirectory = resolve(__dirname, '../../../openapi')
const apps: OpenAPIObject = parse(readFileSync(join(specDirectory, 'apps.openapi.yaml'), 'utf8'))
const prefix = '/api/v1/{organizationId}'

describe('platform Swagger HTTP endpoints', () => {
  let app: INestApplication
  let base: string
  let original: OpenAPIObject
  let document: ReturnType<typeof parse>

  beforeAll(async () => {
    const module = await Test.createTestingModule({ controllers: [BoxController, VolumeController] }).compile()
    app = module.createNestApplication()
    app.setGlobalPrefix('api')
    const dashboard = SwaggerModule.createDocument(app, getOpenApiConfig('https://issuer.example'))
    original = JSON.parse(JSON.stringify(dashboard))
    setupPlatformSwagger(app, dashboard, { clientId: 'test-client', audience: 'test-audience' }, specDirectory)
    await app.listen(0, '127.0.0.1')
    base = await app.getUrl()
    document = await (await fetch(base + '/api-json')).json()
    expect(dashboard).toEqual(original)
  })

  afterAll(async () => app?.close())

  it('serves one document in Swagger UI, JSON and YAML alongside the existing groups', async () => {
    expect(document.openapi).toBe(original.openapi)
    expect(document.paths).toMatchObject(original.paths)
    expect(document.servers).toEqual(original.servers)
    expect(document.components.securitySchemes).toMatchObject(original.components.securitySchemes)
    expect(parse(await (await fetch(base + '/api-yaml')).text())).toEqual(document)
    const html = await (await fetch(base + '/api')).text()
    expect(html).toContain('swagger-ui-init.js')
    const init = await (await fetch(base + '/api/swagger-ui-init.js')).text()
    expect(init).toMatch(/"operationId"\s*:\s*"listApps"/)
    expect(init).not.toMatch(/"urls"\s*:/)
    expect(init).toContain('test-client')
    expect(init).toContain('test-audience')
    expect((await fetch(base + '/api/apps.openapi.yaml')).status).toBe(404)
  })

  it('publishes every CLI operation under Applet with its organization, credentials and same-origin URL', () => {
    for (const [path, item] of Object.entries(apps.paths)) {
      const published = document.paths[prefix + path]
      for (const [method, source] of Object.entries(item)) {
        if (!source.operationId) continue
        const op = published[method]
        expect(op).toMatchObject({
          operationId: source.operationId,
          tags: ['Applet'],
          security: apps.security,
          'x-permissions': source['x-permissions'],
        })
        const server = (op.servers ?? published.servers ?? document.servers)[0]
        expect(new URL(server.url, base).href).toBe(base + '/')
        const parameters = [...(published.parameters ?? []), ...(op.parameters ?? [])].map((param) =>
          param.$ref ? document.components.parameters[param.$ref.split('/').pop()] : param,
        )
        for (const [, name] of (prefix + path).matchAll(/\{([^}]+)\}/g)) {
          expect(parameters).toContainEqual(expect.objectContaining({ name, in: 'path', required: true }))
        }
      }
    }
    for (const [, ref] of JSON.stringify(document).matchAll(/"\$ref":"([^"]+)"/g)) {
      expect(ref).toMatch(/^#\//)
      expect(document).toHaveProperty(ref.slice(2).split('/'))
    }
  })

  it('represents nullable responses, manifest alternatives and deployment kinds in OpenAPI 3.0', () => {
    expect(document.openapi).toMatch(/^3\.0\./)
    const list = document.paths[prefix + '/apps'].get.responses['200'].content['application/json'].schema
    const submit = document.paths[prefix + '/apps/{app}/envs/{env}/deployments'].post.requestBody
    const ajv = new Ajv({ strict: false, validateFormats: false })
    const validateList = ajv.compile({ ...list, components: document.components })
    expect(validateList([{ id: 'a', name: 'demo', status: 'ready', url: null }])).toBe(true)
    expect(validateList([{ id: 'a', name: 'demo', status: 'ready', url: 42 }])).toBe(false)
    const validateDeployment = ajv.compile({
      ...submit.content['application/json'].schema,
      components: document.components,
    })
    expect(validateDeployment({ kind: 'deploy', manifest: 'app = "demo"', snapshot_id: 's' })).toBe(true)
    expect(validateDeployment({ kind: 'apply', manifest: { services: [{ name: 'web' }] } })).toBe(true)
    expect(validateDeployment({ kind: 'apply', manifest: { services: [{}] } })).toBe(false)
    expect(validateDeployment({ kind: 'deploy', manifest: {} })).toBe(false)
    expect(JSON.stringify(document)).not.toMatch(/"const":|"type":\[/)
  })
})