Skip to content

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

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

import { ConflictException, NotFoundException, NotImplementedException } from '@nestjs/common'
import { EntityManager, Repository } from 'typeorm'
import { Box } from '../../box/entities/box.entity'
import { Checkpoint } from '../../box/entities/checkpoint.entity'
import { RegistryCredential } from '../entities/registry-credential.entity'
import { SecretStore } from '../stores/secret.store'
import { RegistriesService } from './registries.service'

const PROXY = 'registry-proxy-abc.a.run.app'
const ORG = '0aaa0000-0000-4000-8000-000000000001'
const REQUEST = { registryHost: 'ghcr.io', repositoryPrefix: 'acme/', username: 'acme-bot', password: 'ghp_x' }

function build({
  store = { put: jest.fn(async () => 'version-1'), destroy: jest.fn(async () => undefined) },
  row = {
    id: 'credential-1',
    organizationId: ORG,
    registryHost: 'ghcr.io',
    repositoryPrefix: 'acme/',
    secretVersion: 'version-1',
  },
  boxes = [] as Partial<Box>[],
  picked = 'credential-1' as string | null,
} = {}) {
  const calls: string[] = []
  const credentials = {
    insert: jest.fn(async () => calls.push('insert')),
    findOneByOrFail: jest.fn(async () => ({ ...row })),
    findOneBy: jest.fn(async () => row),
    delete: jest.fn(async () => calls.push('delete')),
    find: jest.fn(async () =>
      picked === row.id ? [row] : picked ? [{ ...row, id: picked, repositoryPrefix: 'acme/app/' }] : [],
    ),
    manager: {} as EntityManager,
  }
  const builder = {
    where: jest.fn(() => builder),
    andWhere: jest.fn(() => builder),
    select: jest.fn(() => builder),
    getMany: jest.fn(async () => boxes),
  }
  const manager = {
    findOne: jest.fn(async () => credentials.findOneBy()),
    delete: jest.fn(async () => credentials.delete()),
    update: jest.fn(async () => calls.push('update')),
    getRepository: jest.fn((entity) =>
      entity === RegistryCredential
        ? credentials
        : entity === Checkpoint
          ? { find: async () => [] }
          : { createQueryBuilder: () => builder },
    ),
  }
  credentials.manager.transaction = jest.fn(async (_isolation, callback) => callback(manager)) as never
  store.destroy.mockImplementation(async () => {
    calls.push('destroy')
  })
  const service = new RegistriesService(
    credentials as unknown as Repository<RegistryCredential>,
    store as unknown as SecretStore,
  )
  return { service, credentials, store, builder, calls, manager }
}

describe('RegistriesService', () => {
  beforeEach(() => {
    process.env.REGISTRY_PROXY_HOST = PROXY
  })

  afterEach(() => {
    delete process.env.REGISTRY_PROXY_HOST
  })

  describe('create', () => {
    it('writes the password to the store and records only where it went', async () => {
      const { service, credentials, store } = build()

      await service.create(ORG, 'user-1', REQUEST)

      expect(store.put).toHaveBeenCalledWith(expect.any(String), 'ghp_x')
      const [inserted] = credentials.insert.mock.calls[0] as unknown as [Record<string, unknown>]
      expect(inserted).toMatchObject({ registryHost: 'ghcr.io', repositoryPrefix: 'acme/', secretVersion: 'version-1' })
      expect(JSON.stringify(inserted)).not.toContain('ghp_x')
      // The row's id is the secret's name, so the two cannot drift apart.
      expect(inserted.id).toBe((store.put.mock.calls[0] as unknown as [string])[0])
    })

    it('destroys the password again when a second login for the same prefix is refused', async () => {
      const { service, credentials, store } = build()
      credentials.insert.mockRejectedValue(Object.assign(new Error('duplicate'), { code: '23505' }))

      await expect(service.create(ORG, 'user-1', REQUEST)).rejects.toBeInstanceOf(ConflictException)
      expect(store.destroy).toHaveBeenCalledWith('version-1')
    })

    it('codes the refusal of a second login already_exists, so an SDK can tell it from a delete refusal', async () => {
      const { service, credentials } = build()
      credentials.insert.mockRejectedValue(Object.assign(new Error('duplicate'), { code: '23505' }))

      const refusal = await service.create(ORG, 'user-1', REQUEST).then(
        () => fail('a second login for the same prefix was stored'),
        (error: ConflictException) => error,
      )

      expect(refusal.getResponse()).toMatchObject({
        code: 'already_exists',
        message: expect.stringContaining('ghcr.io/acme/ already exists'),
      })
    })

    it('destroys the password on any other failure to record it, and reports that failure', async () => {
      const { service, credentials, store } = build()
      credentials.insert.mockRejectedValue(new Error('connection reset'))

      await expect(service.create(ORG, 'user-1', REQUEST)).rejects.toThrow('connection reset')
      expect(store.destroy).toHaveBeenCalledWith('version-1')
    })

    it('refuses with 501 where there is no proxy to present a login', async () => {
      delete process.env.REGISTRY_PROXY_HOST
      const { service, store } = build()

      const refused = service.create(ORG, 'user-1', REQUEST)

      await expect(refused).rejects.toBeInstanceOf(NotImplementedException)
      // Coded, so an SDK reads it as unsupported rather than a server fault.
      await expect(refused).rejects.toMatchObject({ response: { code: 'unsupported' } })
      expect(store.put).not.toHaveBeenCalled()
    })
  })

  describe('update', () => {
    const replacement = { username: 'new-bot', password: 'new-token' }

    it('updates only the login, then retires the old secret after commit', async () => {
      const { service, credentials, store, manager, calls } = build()
      store.put.mockImplementation(async () => {
        calls.push('put')
        return 'version-2'
      })
      credentials.manager.transaction = jest.fn(async (_isolation, callback) => {
        calls.push('begin')
        const result = await callback(manager)
        calls.push('commit')
        return result
      }) as never

      const updated = await service.update(ORG, 'credential-1', replacement)

      expect(manager.findOne).toHaveBeenCalledWith(RegistryCredential, {
        where: { id: 'credential-1', organizationId: ORG },
        lock: { mode: 'pessimistic_write', onLocked: 'nowait' },
      })
      expect(store.put).toHaveBeenCalledWith(expect.any(String), replacement.password)
      expect((store.put.mock.calls[0] as unknown as [string])[0]).not.toBe('credential-1')
      expect(manager.update).toHaveBeenCalledWith(
        RegistryCredential,
        { id: 'credential-1', organizationId: ORG },
        {
          username: 'new-bot',
          secretVersion: 'version-2',
        },
      )
      expect(updated).toMatchObject({
        id: 'credential-1',
        registryHost: 'ghcr.io',
        repositoryPrefix: 'acme/',
        username: 'new-bot',
      })
      expect(calls).toEqual(['put', 'begin', 'update', 'commit', 'destroy'])
      expect(store.destroy).toHaveBeenCalledWith('version-1')
    })

    it('does not touch either secret when writing the replacement fails', async () => {
      const { service, credentials, store, manager } = build()
      store.put.mockRejectedValue(new Error('Secret store unavailable'))
      await expect(service.update(ORG, 'credential-1', replacement)).rejects.toThrow('Secret store unavailable')
      expect(credentials.manager.transaction).not.toHaveBeenCalled()
      expect(manager.update).not.toHaveBeenCalled()
      expect(store.destroy).not.toHaveBeenCalled()
    })

    it('cleans up only the replacement on an update failure before COMMIT', async () => {
      const { service, credentials, store, manager, calls } = build()
      store.put.mockResolvedValue('version-2')
      manager.update.mockRejectedValue(new Error('Database update failed') as never)
      credentials.manager.transaction = jest.fn(async (_isolation, callback) => {
        try {
          return await callback(manager)
        } catch (error) {
          calls.push('rollback')
          throw error
        }
      }) as never
      await expect(service.update(ORG, 'credential-1', replacement)).rejects.toThrow('Database update failed')
      expect(store.destroy.mock.calls).toEqual([['version-2']])
      expect(calls).toEqual(['rollback', 'destroy'])
    })

    it('cleans the replacement if the transaction cannot start', async () => {
      const { service, credentials, store } = build()
      store.put.mockResolvedValue('version-2')
      credentials.manager.transaction = jest.fn().mockRejectedValue(new Error('Connection unavailable'))

      await expect(service.update(ORG, 'credential-1', replacement)).rejects.toThrow('Connection unavailable')

      expect(store.put).toHaveBeenCalledWith(expect.any(String), replacement.password)
      expect(store.destroy.mock.calls).toEqual([['version-2']])
    })

    it('keeps the committed result when retiring the old secret fails', async () => {
      const { service, store } = build()
      store.put.mockResolvedValue('version-2')
      store.destroy.mockRejectedValue(new Error('Cleanup unavailable'))
      const warn = jest.spyOn((service as any).logger, 'warn').mockImplementation()
      await expect(service.update(ORG, 'credential-1', replacement)).resolves.toMatchObject({
        secretVersion: 'version-2',
      })
      expect(warn).toHaveBeenCalledWith(expect.stringContaining('version-1'))
      expect(warn).toHaveBeenCalledWith(expect.stringContaining('Cleanup unavailable'))
      warn.mockRestore()
    })

    it('preserves the original failure if replacement cleanup also fails', async () => {
      const { service, store, manager } = build()
      store.put.mockResolvedValue('version-2')
      manager.update.mockRejectedValue(new Error('Database update failed') as never)
      store.destroy.mockRejectedValue(new Error('Cleanup unavailable'))
      await expect(service.update(ORG, 'credential-1', replacement)).rejects.toThrow('Database update failed')
      expect(store.destroy.mock.calls).toEqual([['version-2']])
    })

    it('refuses rotation when private registries are disabled', async () => {
      delete process.env.REGISTRY_PROXY_HOST
      const { service, store } = build()
      await expect(service.update(ORG, 'credential-1', replacement)).rejects.toBeInstanceOf(NotImplementedException)
      expect(store.put).not.toHaveBeenCalled()
    })
  })

  describe('delete', () => {
    it('refuses with the ids of the boxes still pulling through it', async () => {
      const { service, store, builder, credentials } = build({
        boxes: [
          { id: 'box-1', image: `${PROXY}/${ORG}/ghcr.io/acme/app:1` },
          { id: 'box-2', image: `${PROXY}/${ORG}/ghcr.io/acme/tool@sha256:${'a'.repeat(64)}` },
        ],
      })

      const refused = service.delete(ORG, 'credential-1')

      await expect(refused).rejects.toBeInstanceOf(ConflictException)
      await expect(refused).rejects.toThrow(/box-1, box-2/)
      expect(store.destroy).not.toHaveBeenCalled()
      // The boxes asked about: this organization's, not destroyed, and pulling
      // through the proxy from this login's host.
      expect(builder.where).toHaveBeenCalledWith('box.organizationId = :organizationId', { organizationId: ORG })
      expect(builder.andWhere).toHaveBeenCalledWith('box.desiredState != :destroyed', { destroyed: 'destroyed' })
      expect(builder.andWhere).toHaveBeenCalledWith('box.image LIKE :through', {
        through: `${PROXY}/${ORG}/ghcr.io/%`,
      })
      expect(credentials.find).toHaveBeenCalledTimes(1)
      expect(credentials.find).toHaveBeenCalledWith({ where: { organizationId: ORG, registryHost: 'ghcr.io' } })
    })

    it('lets a login go when a longer one is what its boxes pull through', async () => {
      const { service, calls } = build({
        boxes: [{ id: 'box-1', image: `${PROXY}/${ORG}/ghcr.io/acme/app:1` }],
        picked: 'a-longer-prefix',
      })

      await service.delete(ORG, 'credential-1')

      expect(calls).toEqual(['destroy', 'delete'])
    })

    it('destroys the password before removing the row', async () => {
      const { service, calls } = build()

      await service.delete(ORG, 'credential-1')

      // The other order, interrupted, leaves a readable password nothing lists.
      expect(calls).toEqual(['destroy', 'delete'])
    })

    it('answers 404 for a login the organization does not have', async () => {
      const { service, credentials } = build()
      credentials.findOneBy.mockResolvedValue(null as never)

      await expect(service.delete(ORG, 'credential-9')).rejects.toBeInstanceOf(NotFoundException)
    })
  })
})