Skip to content

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

4.8 KB
Raw Blame
import { ForbiddenException, NotFoundException } from '@nestjs/common'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Writable } from 'node:stream'
import type { Request as ExpressRequest, Response as ExpressResponse } from 'express'
import { CloudAppInternalController } from './cloud-app-internal.controller'
import { signState } from './engine/enduser/state'

describe('internal hosted App endpoints', () => {
  const organization = '487bcad3-a535-4817-8f48-6209dcd73b41'
  const config = {
    get: (key) =>
      ({ cloudApps: { sessionSecret: 'test-state' }, 'cloudApps.artifactVersion': 'r1', 'proxy.protocol': 'https' })[
        key
      ],
  }
  function fixture(artifactDirectory = '') {
    const internal = jest.fn(async (_request: Request, _organization: string) => new Response(null, { status: 204 }))
    const ingress = jest.fn(
      async (_request: Request, _id: string, _original: ExpressRequest) => new Response('served', { status: 201 }),
    )
    const supervisorOrganization = jest.fn(async () => organization)
    const controller = new CloudAppInternalController(
      { internal, ingress, supervisorOrganization, artifactDirectory } as never,
      config as never,
    )
    return { controller, internal, ingress, supervisorOrganization }
  }
  const request = (suffix: string, headers: Record<string, string> = {}, body?: unknown) =>
    ({ originalUrl: '/api/internal/apps' + suffix, headers, method: body ? 'POST' : 'GET', body }) as ExpressRequest
  const response = () => {
    const chunks: Buffer[] = []
    const stream = Object.assign(
      new Writable({
        write(chunk, _encoding, done) {
          chunks.push(chunk)
          done()
        },
      }),
      { status: jest.fn(), setHeader: jest.fn() },
    )
    return { output: stream as unknown as ExpressResponse, chunks, stream }
  }

  test('passes the app origin path and query to ingress and streams back its status and bytes', async () => {
    const h = fixture()
    const read = request('/ingress/env/account?tab=jobs', { host: 'site.example.test' })
    const out = response()
    await h.controller.ingress('env', read, out.output)
    expect(h.ingress.mock.calls[0][0].url).toBe('https://site.example.test/account?tab=jobs')
    expect(h.ingress.mock.calls[0].slice(1)).toEqual(['env', read])
    expect(out.stream.status).toHaveBeenCalledWith(201)
    expect(Buffer.concat(out.chunks).toString()).toBe('served')
  })

  test('routes supervisor calls by bearer and sign-in callbacks by signed state', async () => {
    const h = fixture()
    await expect(h.controller.supervisor(request('/sv/v1/spec'), response().output)).rejects.toThrow(ForbiddenException)
    await h.controller.supervisor(request('/sv/v1/spec', { authorization: 'Bearer box-test' }), response().output)
    expect(h.supervisorOrganization).toHaveBeenCalledWith('box-test')
    const start = '/auth/start?organization=' + organization
    await h.controller.oauth(request(start), response().output)
    const state = signState('test-state', {
      organization,
      app: 'app',
      env: 'main',
      next: '/',
      provider: 'github',
      vh: 'v',
    })
    await h.controller.oauth(request('/auth/callback/github', {}, { state }), response().output)
    await expect(h.controller.oauth(request('/auth/callback/github?state=invalid'), response().output)).rejects.toThrow(
      ForbiddenException,
    )
    expect(h.internal.mock.calls.map(([request, id]) => [request.url, id])).toEqual([
      ['http://platform.local/sv/v1/spec', organization],
      ['http://platform.local' + start, organization],
      ['http://platform.local/auth/callback/github', organization],
    ])
  })

  test('serves versioned agent text and supervisor bytes with bounded caching', async () => {
    const directory = mkdtempSync(join(tmpdir(), 'app-artifact-'))
    try {
      const h = fixture(directory)
      for (const [file, type, bytes] of [
        ['agent.md', 'text/markdown; charset=utf-8', Buffer.from('# App guide')],
        ['supervisor-linux-amd64', 'application/octet-stream', Buffer.from([0, 255, 7])],
      ] as const) {
        writeFileSync(join(directory, file), bytes)
        const out = response()
        await h.controller.artifact(file, out.output, 'r1')
        expect(out.stream.setHeader).toHaveBeenCalledWith('content-type', type)
        expect(out.stream.setHeader).toHaveBeenCalledWith('cache-control', 'public, max-age=300')
        expect(Buffer.concat(out.chunks)).toEqual(bytes)
      }
      for (const [file, version] of [
        ['agent.md', 'r2'],
        ['unknown', 'r1'],
        ['supervisor-linux-arm64', 'r1'],
      ]) {
        await expect(h.controller.artifact(file, response().output, version)).rejects.toThrow(NotFoundException)
      }
    } finally {
      rmSync(directory, { recursive: true, force: true })
    }
  })
})