The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
import { INestApplication } from '@nestjs/common'
import { getRedisConnectionToken } from '@nestjs-modules/ioredis'
import { Test } from '@nestjs/testing'
import { randomUUID } from 'node:crypto'
import { CombinedAuthGuard } from '../auth/combined-auth.guard'
import { OrgSecretRetirementService } from '../box/services/org-secret-retirement.service'
import { SecretServerClient } from '../box/services/secret-server-client'
import { AuthenticatedRateLimitGuard } from '../common/guards/authenticated-rate-limit.guard'
import { TypedConfigService } from '../config/typed-config.service'
import { OrganizationService } from '../organization/services/organization.service'
import { OrganizationUserService } from '../organization/services/organization-user.service'
import { BoxliteSecretController } from './boxlite-secret.controller'
describe('/api/v1/secrets', () => {
let app: INestApplication
let permissions: string[]
const store = { createOrganizationSecret: jest.fn(), listOrganizationSecrets: jest.fn() }
const retirements = { remove: jest.fn() }
let organizationId: string
const input = {
name: 'openai',
value: 'synthetic',
hosts: ['upstream.example'],
headers: { Authorization: 'Bearer {value}' },
}
async function startApi(
secretStore: Pick<SecretServerClient, 'createOrganizationSecret' | 'listOrganizationSecrets'>,
) {
const module = await Test.createTestingModule({
controllers: [BoxliteSecretController],
providers: [
{ provide: OrgSecretRetirementService, useValue: retirements },
{ provide: SecretServerClient, useValue: secretStore },
{
provide: OrganizationService,
useValue: { findOne: async (id: string) => ({ id }), assertOrganizationIsNotSuspended: jest.fn() },
},
{ provide: OrganizationUserService, useValue: { findOneCached: async () => ({ role: 'owner' }) } },
{ provide: getRedisConnectionToken(), useValue: { get: async () => null, set: async () => 'OK' } },
],
})
.overrideGuard(CombinedAuthGuard)
.useValue({
canActivate(ctx) {
ctx.switchToHttp().getRequest().user = {
userId: 'creator',
role: 'user',
organizationId,
apiKey: { organizationId, permissions },
}
return true
},
})
.overrideGuard(AuthenticatedRateLimitGuard)
.useValue({ canActivate: () => true })
.compile()
const api = module.createNestApplication()
api.setGlobalPrefix('api')
await api.listen(0, '127.0.0.1')
return api
}
beforeAll(async () => {
app = await startApi(store)
})
beforeEach(() => {
organizationId = 'org-a'
jest.clearAllMocks()
})
afterAll(async () => app?.close())
async function create(body: unknown, api = app) {
return fetch((await api.getUrl()) + '/api/v1/secrets', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
})
}
it('derives the organization and creator from identity and enforces the key scope', async () => {
permissions = ['write:boxes']
expect((await create(input)).status).toBe(403)
expect(store.createOrganizationSecret).not.toHaveBeenCalled()
permissions = ['write:secrets']
expect((await create({ ...input, organization_id: 'org-b' })).status).toBe(400)
expect(store.createOrganizationSecret).not.toHaveBeenCalled()
const identity = { id: '1dd00103-6203-450a-86cc-ab12456eca34', name: input.name }
store.createOrganizationSecret.mockResolvedValue(identity)
const response = await create(input)
expect(response.status).toBe(201)
expect(await response.json()).toEqual(identity)
expect(store.createOrganizationSecret).toHaveBeenCalledWith('org-a', 'creator', input)
})
const live = process.env.SECRET_SERVER_URL && process.env.SECRET_SERVER_DEV_TOKEN ? it : it.skip
function liveClient() {
const config = {
'secretServer.enabled': true,
'secretServer.url': process.env.SECRET_SERVER_URL,
'secretServer.devToken': process.env.SECRET_SERVER_DEV_TOKEN,
}
return new SecretServerClient({ get: (key: string) => config[key] } as TypedConfigService)
}
live('lists stored routing metadata through the public API for only the caller’s organization secrets', async () => {
const client = liveClient()
const api = await startApi(client)
const owner = randomUUID()
const foreign = randomUUID()
const boxId = randomUUID().replaceAll('-', '').slice(0, 12)
const policy = {
hosts: ['second.example', 'first.example'],
headers: { Authorization: 'Bearer {value}', 'X-Service-Key': 'prefix-{value}' },
placeholder: 'custom-list-marker',
}
permissions = ['read:secrets', 'write:secrets']
const value = randomUUID()
const secret = { name: 'openai', value, ...policy }
const created = new Map<string, string>()
try {
for (const org of [owner, foreign]) {
organizationId = org
const response = await create(secret, api)
expect(response.status).toBe(201)
const identity = await response.json()
created.set(org, identity.id)
expect(identity).toEqual({ id: expect.any(String), name: secret.name })
}
expect(created.get(owner)).not.toBe(created.get(foreign))
const [privateRef] = await client.storeBoxSecrets(boxId, owner, 'creator', [{ ...secret, name: 'private' }])
expect(privateRef.secretId).toEqual(expect.any(String))
for (const org of [owner, foreign]) {
organizationId = org
const response = await fetch((await api.getUrl()) + '/api/v1/secrets')
expect(response.status).toBe(200)
const body = await response.text()
expect(body).not.toContain(value)
expect(JSON.parse(body)).toEqual({ secrets: [{ id: created.get(org), name: secret.name, ...policy }] })
}
} finally {
try {
await client.retireBoxSecrets(owner, boxId)
for (const [org, id] of created) await client.deleteOrganizationSecret(org, id)
} finally {
await api.close()
}
}
})
live(
'returns all 101 organization secrets in default pages of 100 and 1',
async () => {
const client = liveClient()
const api = await startApi(client)
const org = randomUUID()
organizationId = org
permissions = ['read:secrets', 'write:secrets']
const ids: string[] = []
try {
for (let i = 0; i < 101; i++) {
const response = await create({ ...input, name: 'key-' + i }, api)
expect(response.status).toBe(201)
ids.push((await response.json()).id)
}
const url = (await api.getUrl()) + '/api/v1/secrets'
const first = await fetch(url)
expect(first.status).toBe(200)
const page = await first.json()
expect(page.secrets).toHaveLength(100)
expect(page.next_page_token).toEqual(expect.any(String))
const next = await fetch(url + '?pageToken=' + encodeURIComponent(page.next_page_token))
expect(next.status).toBe(200)
const last = await next.json()
expect(last.secrets).toHaveLength(1)
expect(last).not.toHaveProperty('next_page_token')
expect([...page.secrets, ...last.secrets].map((row) => row.id)).toEqual(ids.sort())
} finally {
try {
for (const id of ids) await client.deleteOrganizationSecret(org, id)
} finally {
await api.close()
}
}
},
30_000,
)
it('rejects pageSize 101 and asks the store for 101 rows for pageSize 100', async () => {
permissions = ['read:secrets']
store.listOrganizationSecrets.mockResolvedValue([])
const url = (await app.getUrl()) + '/api/v1/secrets'
expect((await fetch(url + '?pageSize=101')).status).toBe(400)
expect(store.listOrganizationSecrets).not.toHaveBeenCalled()
expect((await fetch(url + '?pageSize=100')).status).toBe(200)
expect(store.listOrganizationSecrets).toHaveBeenCalledWith('org-a', undefined, 101)
})
it('paginates secret metadata and binds the token to the authenticated organization', async () => {
const url = (await app.getUrl()) + '/api/v1/secrets'
permissions = ['write:secrets']
expect((await fetch(url)).status).toBe(403)
expect(store.listOrganizationSecrets).not.toHaveBeenCalled()
permissions = ['read:secrets']
const policy = { hosts: input.hosts, headers: input.headers, placeholder: 'custom' }
const one = { id: '10000000-0000-4000-8000-000000000001', name: 'first', ...policy }
const two = { id: '20000000-0000-4000-8000-000000000002', name: 'second', ...policy }
store.listOrganizationSecrets.mockResolvedValueOnce([one, two]).mockResolvedValueOnce([two])
const first = await fetch(url + '?pageSize=1')
expect(first.status).toBe(200)
expect(first.headers.get('cache-control')).toBe('no-store')
const page = await first.json()
expect(page).toEqual({ secrets: [one], next_page_token: expect.any(String) })
const next = url + '?pageSize=1&pageToken=' + encodeURIComponent(page.next_page_token)
expect(await (await fetch(next)).json()).toEqual({ secrets: [two] })
expect(store.listOrganizationSecrets.mock.calls).toEqual([
['org-a', undefined, 2],
['org-a', one.id, 2],
])
organizationId = 'org-b'
expect((await fetch(next)).status).toBe(400)
for (const query of ['pageSize=0', 'pageSize=1.5', 'pageSize=x', 'pageToken=x', 'organization_id=org-a']) {
expect((await fetch(url + '?' + query)).status).toBe(400)
}
expect(store.listOrganizationSecrets).toHaveBeenCalledTimes(2)
})
it('requires write permission and a UUID for deletion', async () => {
const url = (await app.getUrl()) + '/api/v1/secrets/'
const id = '1dd00103-6203-450a-86cc-ab12456eca34'
permissions = ['read:secrets']
expect((await fetch(url + id, { method: 'DELETE' })).status).toBe(403)
permissions = ['write:secrets']
expect((await fetch(url + 'openai', { method: 'DELETE' })).status).toBe(400)
expect(retirements.remove).not.toHaveBeenCalled()
const response = await fetch(url + id, { method: 'DELETE' })
expect(response.status).toBe(204)
expect(await response.text()).toBe('')
expect(retirements.remove).toHaveBeenCalledWith('org-a', id)
})
})