Skip to content

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

3.5 KB
Raw Blame
import { ExecutionContext, ForbiddenException, INestApplication } from '@nestjs/common'
import { Test } from '@nestjs/testing'
import { CombinedAuthGuard } from '../auth/combined-auth.guard'
import { OrganizationResourceActionGuard } from '../organization/guards/organization-resource-action.guard'
import { CloudAppController } from './cloud-app.controller'
import { CloudAppService } from './cloud-app.service'

describe('organization App management controller', () => {
  const organizationId = '00000000-0000-4000-8000-000000000001'
  const member = { organizationId, userId: 'member' }
  const identity = { ...member, actor: 'user:member', permissions: ['read:apps', 'write:apps'] }
  const principal = jest.fn(() => identity)
  const management = jest.fn<Promise<Response>, [Request, typeof identity]>()
  let app: INestApplication
  let url: string

  beforeAll(async () => {
    const module = await Test.createTestingModule({
      controllers: [CloudAppController],
      providers: [{ provide: CloudAppService, useValue: { principal, management } }],
    })
      .overrideGuard(CombinedAuthGuard)
      .useValue({
        canActivate: (ctx: ExecutionContext) => {
          ctx.switchToHttp().getRequest().user = member
          return true
        },
      })
      .overrideGuard(OrganizationResourceActionGuard)
      .useValue({ canActivate: () => true })
      .compile()
    app = module.createNestApplication()
    app.setGlobalPrefix('api')
    await app.listen(0, '127.0.0.1')
    url = (await app.getUrl()) + '/api/v1/' + organizationId
  })
  afterAll(() => app?.close())
  beforeEach(() => jest.clearAllMocks())

  it('forwards the organization collection and a nested mutation with their original method, query and body', async () => {
    management.mockResolvedValueOnce(Response.json([{ name: 'journal' }]))
    const list = await fetch(url + '/apps')
    expect(await list.json()).toEqual([{ name: 'journal' }])
    expect(principal).toHaveBeenCalledWith(member, 'GET', '/apps')
    expect(management.mock.calls[0]![0].url).toBe('http://platform.local/v1/apps')

    const path = '/apps/journal/envs/main/deployments'
    const payload = { kind: 'apply', message: 'review copy' }
    management.mockResolvedValueOnce(Response.json({ number: 2 }, { status: 202, headers: { location: path + '/2' } }))
    const created = await fetch(url + path + '?view=full', {
      method: 'POST',
      headers: { 'content-type': 'application/json', 'idempotency-key': 'test-release' },
      body: JSON.stringify(payload),
    })
    expect({ status: created.status, location: created.headers.get('location'), body: await created.json() }).toEqual({
      status: 202,
      location: path + '/2',
      body: { number: 2 },
    })
    expect(principal).toHaveBeenLastCalledWith(member, 'POST', path)
    const [input, caller] = management.mock.calls[1]!
    expect(caller).toEqual(identity)
    expect([input.method, input.url, input.headers.get('idempotency-key'), await input.json()]).toEqual([
      'POST',
      'http://platform.local/v1' + path + '?view=full',
      'test-release',
      payload,
    ])
  })

  it('returns the organization authorization error before dispatching a management request', async () => {
    principal.mockImplementationOnce(() => {
      throw new ForbiddenException('App permission required')
    })
    const denied = await fetch(url + '/apps/journal', { method: 'DELETE' })
    expect(denied.status).toBe(403)
    expect((await denied.json()).message).toBe('App permission required')
    expect(management).not.toHaveBeenCalled()
  })
})