Skip to content

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

76.2 KB
Raw Blame
/*
 * Copyright 2025 BoxLite AI
 * SPDX-License-Identifier: AGPL-3.0
 */

import { ForbiddenException, NotFoundException } from '@nestjs/common'
import { plainToInstance } from 'class-transformer'
import { BoxService } from './box.service'
import { BoxState } from '../enums/box-state.enum'
import { BoxDesiredState } from '../enums/box-desired-state.enum'
import { RunnerState } from '../enums/runner-state.enum'
import { BadRequestError } from '../../exceptions/bad-request.exception'
import { BoxCreationLimitExceededError } from '../errors/box-creation-limit.error'
import { BoxEvents } from '../constants/box-events.constants'
import Redis from 'ioredis'
import { Repository } from 'typeorm'
import { Image } from '../../image/entities/image.entity'
import { ImageVersion } from '../../image/entities/image-version.entity'
import { ImageAdmissionService } from '../../image/services/image-admission.service'
import { ImageResolverService } from '../../image/services/image-resolver.service'
import { RegistryCredentialService } from '../../registry/services/registry-credential.service'
import { CreateBoxDto as RestCreateBoxDto } from '../../boxlite-rest/dto/create-box.dto'
import { createBoxToCreateBox } from '../../boxlite-rest/mappers/box-to-box.mapper'
import { Context } from '../../common/context/context'
import { OrganizationService } from '../../organization/services/organization.service'
import { CreateBoxDto } from '../dto/create-box.dto'
import { Organization } from '../../organization/entities/organization.entity'
import { SecretServerClient } from './secret-server-client'
import { createServer } from 'node:http'
import { AddressInfo } from 'node:net'
import { Volume } from '../entities/volume.entity'
import { CheckpointRecoverService } from './checkpoint-recover.service'
import { VolumeService } from './volume.service'
import { VolumeState } from '../enums/volume-state.enum'
import { Test } from '@nestjs/testing'
import { BoxliteBoxController } from '../../boxlite-rest/boxlite-box.controller'
import { BoxStateWaiterService } from './box-state-waiter.service'
import { CommerceBoxLimitService } from '../../boxlite-rest/commerce-box-limit.service'
import { CombinedAuthGuard } from '../../auth/combined-auth.guard'
import { OrganizationResourceActionGuard } from '../../organization/guards/organization-resource-action.guard'
import { AuthenticatedRateLimitGuard } from '../../common/guards/authenticated-rate-limit.guard'
import { BoxUsageService } from '../../usage/services/box-usage.service'
import { OrganizationResourcePermission } from '../../organization/enums/organization-resource-permission.enum'

const disabledSecretServer = () => new SecretServerClient({ get: () => false } as any)

/** Records every reason as it came, which is what a failure it cannot explain gets. */
const passThroughPullFailures = () => ({ reasonFor: jest.fn(async (_box: unknown, reason: string) => reason) }) as any

// ensureStartedForProxy only touches boxRepository + eventEmitter +
// organizationService; every other injected dependency is irrelevant.
function makeService() {
  const boxRepository = {
    findOneByIdOrName: jest.fn(),
    conditionalStartForProxy: jest.fn(),
    insert: jest.fn(),
  } as any
  const eventEmitter = { emit: jest.fn(), emitAsync: jest.fn() } as any
  // assertOrganizationIsNotSuspended mirrors the real implementation: throw
  // ForbiddenException when the org is suspended, no-op otherwise.
  const organizationService = {
    assertOrganizationIsNotSuspended: jest.fn((org: any) => {
      if (org?.suspended) {
        throw new ForbiddenException('Organization is suspended')
      }
    }),
  } as any
  const noop = {} as any
  const service = new BoxService(
    boxRepository, // boxRepository
    noop, // runnerRepository
    noop, // runnerService
    noop, // boxExitCodeService
    noop, // volumeService
    noop, // configService
    noop, // warmPoolService
    eventEmitter, // eventEmitter
    organizationService, // organizationService
    noop, // runnerAdapterFactory
    noop, // redis
    noop, // regionService
    noop, // boxLookupCacheInvalidationService
    noop, // boxActivityService
    noop, // jobRepository
    noop, // jobService
    noop, // imageAdmissionService
    noop, // imageResolverService
    noop, // imageRegistrarService
    noop, // imagePreparationService
    passThroughPullFailures(), // imagePullFailureService
    {} as any, // organizationBoxLimits (unused by these lifecycle tests)
    disabledSecretServer(),
    noop,
  )
  return { service, boxRepository, eventEmitter, organizationService }
}

const activeOrg = { id: 'org-1', suspended: false } as any
const suspendedOrg = { id: 'org-1', suspended: true } as any

const stoppedBox = {
  id: 'box-1',
  state: BoxState.STOPPED,
  desiredState: BoxDesiredState.STOPPED,
  pending: false,
}

describe('BoxService.ensureStartedForProxy', () => {
  // The control plane never writes box.state directly; like start(), it flips
  // desiredState and lets the runner's reported state catch up. The proxied
  // call has already auto-started the VM in the runtime, so box_sync will
  // report STARTED and — now that desiredState agrees — sync-states will not
  // stop it back.
  it('flips a cleanly-stopped box to desiredState=STARTED and emits STARTED', async () => {
    const { service, boxRepository, eventEmitter } = makeService()
    jest.spyOn(service, 'findOneByIdOrName').mockResolvedValue(stoppedBox as any)
    boxRepository.conditionalStartForProxy.mockResolvedValue({
      ...stoppedBox,
      pending: true,
      desiredState: BoxDesiredState.STARTED,
    })

    await service.ensureStartedForProxy('box-1', activeOrg)

    expect(boxRepository.conditionalStartForProxy).toHaveBeenCalledWith('box-1', 'org-1')
    expect(eventEmitter.emit).toHaveBeenCalledWith(BoxEvents.STARTED, expect.anything())
    // Also raise the desired-state event start() raises, so the notification
    // gateway and analytics observe the STOPPED→STARTED flip on autostart too.
    expect(eventEmitter.emit).toHaveBeenCalledWith(BoxEvents.DESIRED_STATE_UPDATED, expect.anything())
  })

  // Same gate as start() (~line 790). Without this, a suspended org could
  // exec / files / metrics a STOPPED box back to STARTED, bypassing the
  // start-time guard.
  it('throws ForbiddenException for a suspended organization', async () => {
    const { service, boxRepository, eventEmitter } = makeService()

    await expect(service.ensureStartedForProxy('box-1', suspendedOrg)).rejects.toThrow(ForbiddenException)

    expect(boxRepository.conditionalStartForProxy).not.toHaveBeenCalled()
    expect(eventEmitter.emit).not.toHaveBeenCalled()
  })

  it('is a no-op for an already-started box (idempotent)', async () => {
    const { service, boxRepository, eventEmitter } = makeService()
    jest.spyOn(service, 'findOneByIdOrName').mockResolvedValue({
      ...stoppedBox,
      state: BoxState.STARTED,
      desiredState: BoxDesiredState.STARTED,
    } as any)

    await service.ensureStartedForProxy('box-1', activeOrg)

    expect(boxRepository.conditionalStartForProxy).not.toHaveBeenCalled()
    expect(eventEmitter.emit).not.toHaveBeenCalled()
  })

  it('does not revive a box the user asked to destroy', async () => {
    const { service, boxRepository } = makeService()
    jest.spyOn(service, 'findOneByIdOrName').mockResolvedValue({
      ...stoppedBox,
      desiredState: BoxDesiredState.DESTROYED,
    } as any)

    await service.ensureStartedForProxy('box-1', activeOrg)

    expect(boxRepository.conditionalStartForProxy).not.toHaveBeenCalled()
  })

  it('does not touch a box already mid-transition (pending)', async () => {
    const { service, boxRepository } = makeService()
    jest.spyOn(service, 'findOneByIdOrName').mockResolvedValue({ ...stoppedBox, pending: true } as any)

    await service.ensureStartedForProxy('box-1', activeOrg)

    expect(boxRepository.conditionalStartForProxy).not.toHaveBeenCalled()
  })

  it('returns the latest box without emitting when another request wins the start race', async () => {
    const { service, boxRepository, eventEmitter } = makeService()
    jest.spyOn(service, 'findOneByIdOrName').mockResolvedValue(stoppedBox as any)
    boxRepository.conditionalStartForProxy.mockResolvedValue(null)

    const result = await service.ensureStartedForProxy('box-1', activeOrg)

    expect(result).toBe(stoppedBox)
    expect(eventEmitter.emit).not.toHaveBeenCalled()
  })

  it('does not emit and preserves an unexpected database failure', async () => {
    const { service, boxRepository, eventEmitter } = makeService()
    jest.spyOn(service, 'findOneByIdOrName').mockResolvedValue(stoppedBox as any)
    const databaseError = new Error('db connection lost')
    boxRepository.conditionalStartForProxy.mockRejectedValue(databaseError)

    await expect(service.ensureStartedForProxy('box-1', activeOrg)).rejects.toBe(databaseError)
    expect(eventEmitter.emit).not.toHaveBeenCalled()
  }) // Unexpected database errors must remain visible to callers.
})

function makeNetworkTunnelService() {
  const configService = {
    getOrThrow: jest.fn((key: string) => {
      if (key === 'proxy.domain') return 'proxy.example.test'
      if (key === 'proxy.protocol') return 'https'
      throw new Error(`unexpected config key ${key}`)
    }),
  } as any
  const regionService = { findOne: jest.fn().mockResolvedValue(null) } as any
  const noop = {} as any
  const service = new BoxService(
    noop,
    noop,
    noop, // runnerService
    noop, // boxExitCodeService
    noop,
    configService,
    noop,
    noop,
    noop,
    noop,
    noop,
    regionService,
    noop,
    noop,
    noop, // jobRepository
    noop, // jobService
    noop, // imageAdmissionService
    noop, // imageResolverService
    noop, // imageRegistrarService
    noop, // imagePreparationService
    passThroughPullFailures(), // imagePullFailureService
    {} as any, // organizationBoxLimits (unused by these lifecycle tests)
    disabledSecretServer(),
    noop,
  )
  jest.spyOn(service, 'findOneByIdOrName').mockResolvedValue({
    id: 'MixedCaseBox',
    region: 'region-1',
  } as any)
  return service
}

describe('BoxService network tunnel URLs', () => {
  it('creates a case-safe endpoint for an SDK tunnel', async () => {
    const service = makeNetworkTunnelService()

    const result = await service.getNetworkTunnelUrl('MixedCaseBox', 'org-1', 3000)

    expect(result).toBe('https://3000-d-4d6978656443617365426f78.proxy.example.test')
  })
})

describe('BoxService image reporting', () => {
  function makeService(boxState: BoxState, imageIsOrgOwned: boolean | null = true) {
    const box = {
      id: 'box-1',
      organizationId: 'org-1',
      runnerId: 'runner-1',
      image: 'quay.io/acme/app:v1',
      imageIsOrgOwned,
      state: boxState,
    }
    const service = Object.create(BoxService.prototype) as BoxService
    Object.assign(service as any, {
      // The ERROR case runs on past the image report into the real state
      // update, so the write it ends with has to exist.
      boxRepository: { findOne: jest.fn().mockResolvedValue(box), updateWhere: jest.fn() },
      logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },
      imageRegistrarService: { onBoxStarted: jest.fn().mockResolvedValue(undefined) },
      imagePullFailureService: passThroughPullFailures(),
    })
    return {
      service,
      registrar: (service as any).imageRegistrarService,
      pullFailures: (service as any).imagePullFailureService,
    }
  }

  const reported = { digest: `sha256:${'a'.repeat(64)}`, sizeBytes: 4096 }

  /**
   * The report arrives on a state the control plane usually already has: it
   * also learns a box is up by polling the runner, and whichever observation
   * lands first makes the other a no-op transition. Recording the image has to
   * survive that, or the catalog fills only when the race happens to go one way.
   */
  it('records the image even when the reported state is the one already stored', async () => {
    const { service, registrar } = makeService(BoxState.STARTED)

    await service.updateState('box-1', BoxState.STARTED, false, undefined, reported)

    expect(registrar.onBoxStarted).toHaveBeenCalledWith(
      'org-1',
      { ref: 'quay.io/acme/app:v1', isOrgOwned: true, runnerId: 'runner-1' },
      reported,
    )
  })

  /**
   * The registrar is told whose image this is rather than deciding, and what it
   * is told is what the box recorded when it was created. Passing the recorded
   * `false` through is the whole fix: recomputing here would ask the curated
   * set as it stands now, which is not the set this box was created against.
   */
  it('passes on the ownership the box recorded, not a fresh look at the curated set', async () => {
    const { service, registrar } = makeService(BoxState.STARTED, false)

    await service.updateState('box-1', BoxState.STARTED, false, undefined, reported)

    expect(registrar.onBoxStarted).toHaveBeenCalledWith(
      'org-1',
      { ref: 'quay.io/acme/app:v1', isOrgOwned: false, runnerId: 'runner-1' },
      reported,
    )
  })

  /**
   * A pull that failed reports ERROR. An image that never booted must not be in
   * the catalog, where it would count against the organization's limit and be
   * handed to the next box as if it had worked.
   */
  it('records nothing when the box is reporting an error', async () => {
    const { service, registrar } = makeService(BoxState.STARTED)

    await service.updateState('box-1', BoxState.ERROR, false, 'Failed to pull artifact image', reported)

    expect(registrar.onBoxStarted).not.toHaveBeenCalled()
  })

  /**
   * A runner may report why a box failed, and for a private image that reason
   * names the registry proxy ref it pulled. What is stored is what the tenant
   * reads, so it names the upstream image they asked for.
   */
  it('stores a reported reason with the upstream image in place of the registry proxy ref', async () => {
    const proxy = 'registry-proxy-abc.a.run.app'
    process.env.REGISTRY_PROXY_HOST = proxy
    try {
      const { service } = makeService(BoxState.STARTED)
      const proxied = `${proxy}/0aaa0000-0000-4000-8000-000000000001/ghcr.io/acme/app:1`

      await service.updateState('box-1', BoxState.ERROR, false, `Failed to pull image '${proxied}'`)

      expect((service as any).boxRepository.updateWhere).toHaveBeenCalledWith(
        'box-1',
        expect.objectContaining({
          updateData: expect.objectContaining({ errorReason: "Failed to pull image 'ghcr.io/acme/app:1'" }),
        }),
      )
    } finally {
      delete process.env.REGISTRY_PROXY_HOST
    }
  })

  /**
   * A runner that reports a failed pull as a state, rather than through a job,
   * gets its reason explained the same way, after the proxy's address is out
   * of it. A state that is not an error carries no failure to explain.
   */
  it('explains the reason of an error report, and only of an error report', async () => {
    const { service, pullFailures } = makeService(BoxState.STARTED)
    pullFailures.reasonFor.mockResolvedValue('explained')

    await service.updateState('box-1', BoxState.ERROR, false, 'failed to pull manifest [MANIFEST_UNKNOWN]: x')

    expect(pullFailures.reasonFor).toHaveBeenCalledWith(
      expect.objectContaining({ id: 'box-1' }),
      'failed to pull manifest [MANIFEST_UNKNOWN]: x',
    )
    expect((service as any).boxRepository.updateWhere).toHaveBeenCalledWith(
      'box-1',
      expect.objectContaining({ updateData: expect.objectContaining({ errorReason: 'explained' }) }),
    )

    pullFailures.reasonFor.mockClear()
    await service.updateState('box-1', BoxState.STOPPED, false, 'stopped by the user')
    expect(pullFailures.reasonFor).not.toHaveBeenCalled()
  })

  /**
   * The state update is what the control plane acts on; a lost registration
   * only costs the next create one re-resolution.
   */
  it('does not fail the state update when registration throws', async () => {
    const { service, registrar } = makeService(BoxState.STARTED)
    registrar.onBoxStarted.mockRejectedValue(new Error('conflict'))

    await expect(service.updateState('box-1', BoxState.STARTED, false, undefined, reported)).resolves.toBeUndefined()
  })
})

describe('BoxService stale runner state reports', () => {
  function makeLifecycleService(box: { id: string; state: BoxState; desiredState: BoxDesiredState; pending: boolean }) {
    const service = Object.create(BoxService.prototype) as BoxService
    const updateWhere = jest.fn()
    Object.assign(service as any, {
      boxRepository: { findOne: jest.fn().mockResolvedValue(box), updateWhere },
      logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },
      imageRegistrarService: { onBoxStarted: jest.fn().mockResolvedValue(undefined) },
      imagePullFailureService: passThroughPullFailures(),
    })
    return { service, updateWhere, box }
  }

  /**
   * A stale runner snapshot can say a box that is already up is still creating
   * (a configured-but-never-booted local record folds into Creating). Writing
   * it would walk STARTED back to CREATING, leave desiredState at STARTED, and
   * the pending invariant would then block destroy with "state change in
   * progress". The report is stale, not the box: it is acknowledged without a
   * write, so an older runner gains nothing from retrying.
   */
  it('ignores a stale creating report for a started box without writing', async () => {
    const { service, updateWhere, box } = makeLifecycleService({
      id: 'box-1',
      state: BoxState.STARTED,
      desiredState: BoxDesiredState.STARTED,
      pending: false,
    })

    await expect(service.updateState('box-1', BoxState.CREATING)).resolves.toBeUndefined()

    expect(updateWhere).not.toHaveBeenCalled()
    expect(box.state).toBe(BoxState.STARTED)
    expect(box.desiredState).toBe(BoxDesiredState.STARTED)
    expect(box.pending).toBe(false)
  })

  /**
   * Only the stale regression is filtered. A real runtime exit reported by the
   * runner is news the control plane must record.
   */
  it('still records a stopped report for a started box', async () => {
    const { service, updateWhere } = makeLifecycleService({
      id: 'box-1',
      state: BoxState.STARTED,
      desiredState: BoxDesiredState.STARTED,
      pending: false,
    })

    await service.updateState('box-1', BoxState.STOPPED)

    expect(updateWhere).toHaveBeenCalledWith(
      'box-1',
      expect.objectContaining({
        updateData: expect.objectContaining({ state: BoxState.STOPPED, desiredState: BoxDesiredState.STOPPED }),
      }),
    )
  })

  /**
   * An error report from a runner names a real failure and may mark the box
   * recoverable; filtering it would leave the control plane believing a dead
   * box is up.
   */
  it('still records an error report for a started box', async () => {
    const { service, updateWhere } = makeLifecycleService({
      id: 'box-1',
      state: BoxState.STARTED,
      desiredState: BoxDesiredState.STARTED,
      pending: false,
    })

    await service.updateState('box-1', BoxState.ERROR, true, 'runtime failed')

    expect(updateWhere).toHaveBeenCalledWith(
      'box-1',
      expect.objectContaining({
        updateData: expect.objectContaining({
          state: BoxState.ERROR,
          recoverable: true,
          errorReason: 'runtime failed',
        }),
      }),
    )
  })
})

describe('BoxService inbound defaults', () => {
  function makeCreateService(overrides: Record<string, unknown> = {}) {
    const boxRepository = {
      insert: jest.fn(async (box: any) => box),
      manager: {
        query: jest.fn(async (_sql, [_organizationId, environmentId]) =>
          environmentId === 'missing' ? [] : [{ id: environmentId === 'other-app' ? 'app-b' : 'app-a' }],
        ),
      },
    } as any
    const warmPoolService = { fetchWarmPoolBox: jest.fn().mockResolvedValue(undefined) }
    const runner = { id: 'runner-1', draining: false, state: RunnerState.READY }
    const runnerService = {
      getRandomAvailableRunner: jest.fn().mockResolvedValue(runner),
    }
    const service = Object.create(BoxService.prototype) as BoxService
    Object.assign(service as any, {
      getValidatedOrDefaultRegion: jest.fn().mockResolvedValue({ id: 'region-1' }),
      getValidatedOrDefaultClass: jest.fn().mockReturnValue('small'),
      organizationService: {
        assertOrganizationIsNotSuspended: jest.fn(),
        isNestedVirtualizationEnabled: jest.fn().mockResolvedValue(false),
      },
      organizationBoxLimits: { resolve: jest.fn(async (organization) => organization) },
      redis: { exists: jest.fn().mockResolvedValue(1) },
      logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },
      warmPoolService,
      runnerService,
      boxRepository,
      eventEmitter: { emitAsync: jest.fn().mockResolvedValue(undefined) },
      toBoxDto: jest.fn((box) => box),
      imageAdmissionService: {
        assert: jest.fn().mockResolvedValue(undefined),
        spendColdPullBudget: jest.fn().mockResolvedValue(undefined),
      },
      imageResolverService: {
        resolve: jest.fn().mockResolvedValue({ ref: 'quay.io/acme/app@sha256:resolved', isOrgOwned: true }),
      },
      secretServerClient: disabledSecretServer(),
      configService: {
        getOrThrow: jest.fn((key: string) => {
          if (key === 'volume.filestoreInstances') {
            return { instances: [{ instance: 'ml-scratch', projectId: 'boxlite-dev', zone: 'asia-southeast1-b' }] }
          }
          throw new Error(`unexpected config key ${key}`)
        }),
      },
      filestoreInstanceResolver: {
        resolve: jest.fn().mockResolvedValue({ server: '10.0.0.7', export: '/vol1' }),
      },
      ...overrides,
    })
    return { service, boxRepository, runnerService, warmPoolService }
  }

  it('CI platform ownership forces fresh creation and forwards the transaction callback', async () => {
    const { service, boxRepository, warmPoolService } = makeCreateService({
      imageResolverService: { resolve: jest.fn().mockResolvedValue({ ref: 'ubuntu:22.04', isOrgOwned: false }) },
    })
    warmPoolService.fetchWarmPoolBox.mockRejectedValue(new Error('Warm assignment cannot record this ownership'))
    const transaction = { query: jest.fn() }
    const onPersist = jest.fn(async (_tx, _box) => undefined)
    boxRepository.insert.mockImplementation(async (box, _limit, callback) => {
      await callback(transaction, box)
      return box
    })
    const result = await service.create({ image: 'ubuntu:22.04', name: 'ci-native' }, activeOrg, Context.user(), {
      maxCreatedBoxes: 7,
      onPersist,
    })
    expect(warmPoolService.fetchWarmPoolBox).not.toHaveBeenCalled()
    expect(onPersist).toHaveBeenCalledWith(
      transaction,
      expect.objectContaining({ id: result.id, organizationId: activeOrg.id }),
    )
    expect(boxRepository.insert).toHaveBeenCalledWith(expect.objectContaining({ id: result.id }), 7, onPersist)
  })

  describe('Secret Server forwarding', () => {
    const secrets = [
      { name: 'first', value: 'private-first', hosts: ['first.example'], headers: { Authorization: 'Bearer {value}' } },
      { name: 'second', value: 'private-second', hosts: ['second.example'], headers: { 'x-key': '{value}' } },
    ]
    const ids = ['11111111-1111-4111-8111-111111111111', '22222222-2222-4222-8222-222222222222']

    async function fixture(status = 201, enabled = true) {
      let transfer: { boxId: string; payload: any; insertCalls: number }
      const server = createServer(async (request, response) => {
        const chunks: Buffer[] = []
        for await (const chunk of request) chunks.push(chunk)
        transfer = {
          boxId: request.url.split('/')[4],
          payload: JSON.parse(Buffer.concat(chunks).toString()),
          insertCalls: persist.mock.calls.length,
        }
        if (status === -1) {
          response.writeHead(201)
          response.write('{')
          return
        }
        response.writeHead(status)
        response.end(
          JSON.stringify({
            secrets: transfer.payload.secrets.map(({ name }, i) => ({ name, secret_id: ids[i] })).reverse(),
          }),
        )
      })
      await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
      const values = {
        'secretServer.enabled': enabled,
        'secretServer.url': `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
        'secretServer.devToken': 'test-token',
      }
      const { service, boxRepository, warmPoolService } = makeCreateService({
        secretServerClient: new SecretServerClient({ get: (key: string) => values[key] } as any),
      })
      const persist = jest.fn(async (box) => box)
      const manager = { query: jest.fn(async () => [[{ box_id: 'claimed' }], 1]) }
      Object.assign(boxRepository, { manager })
      boxRepository.insert.mockImplementation(async (box, _limit, callback, initialize) => {
        await initialize?.(manager)
        await persist(box)
        await callback?.(manager, box)
        return box
      })
      const events = (service as any).eventEmitter
      return {
        service,
        boxRepository,
        warmPoolService,
        events,
        persist,
        transfer: () => transfer,
        close: async () => {
          server.closeAllConnections()
          await new Promise<void>((resolve) => server.close(() => resolve()))
        },
      }
    }

    it('forwards with the generated ID before insertion, callback, and creation event', async () => {
      const f = await fixture()
      const onPersist = jest.fn()
      const snapshots: unknown[] = []
      f.persist.mockImplementation(async (box) => {
        snapshots.push(structuredClone(box.secrets))
        return box
      })
      try {
        const box = await f.service.create({ name: 'forwarded', secrets }, activeOrg, Context.user(), {
          createdBy: 'authenticated-user',
          onPersist,
        })
        const sent = f.transfer()
        expect(sent.insertCalls).toBe(0)
        expect(sent.boxId).toBe(box.id)
        expect(sent.boxId).toMatch(/^[a-zA-Z0-9]{12}$/)
        expect(sent.payload).toMatchObject({ org_id: activeOrg.id, created_by: 'authenticated-user', secrets })
        const refs = secrets.map(({ name, hosts, headers }, i) => ({
          name,
          hosts,
          headers,
          placeholder: `<BOXLITE_SECRET:${name}>`,
          secretId: ids[i],
        }))
        expect(snapshots).toEqual([refs])
        expect(onPersist.mock.calls[0][1].secrets).toEqual(refs)
        expect(f.events.emitAsync).toHaveBeenCalledWith(
          BoxEvents.CREATED,
          expect.objectContaining({ box: expect.objectContaining({ secrets: refs }) }),
        )
        expect(JSON.stringify(f.events.emitAsync.mock.calls)).not.toMatch(/private-first|private-second|"value"/)
        expect(f.warmPoolService.fetchWarmPoolBox).not.toHaveBeenCalled()
      } finally {
        await f.close()
      }
    })

    it.each([503, 401, -1])(
      'fails before insertion and events on transfer status %s (-1 stalls)',
      async (status) => {
        const f = await fixture(status)
        try {
          await expect(
            f.service.create({ name: 'refused', secrets }, activeOrg, Context.user(), { createdBy: 'user' }),
          ).rejects.toMatchObject({ status: 503, response: { code: 'secret_store_unavailable' } })
          expect(f.persist).not.toHaveBeenCalled()
          expect(f.events.emitAsync).not.toHaveBeenCalled()
        } finally {
          await f.close()
        }
      },
      10000,
    )

    describe.each(['direct', 'rest'])('secret name admission through %s create', (path) => {
      it.each([
        ['key', 'key'],
        ['key', 'KEY'],
        ['open-ai', 'OPEN_AI'],
        ['key😀', 'KEY_'],
      ])('rejects conflicting names %s / %s before transfer when enabled', async (first, second) => {
        const f = await fixture()
        const onPersist = jest.fn()
        const input = { secrets: secrets.map((secret, i) => ({ ...secret, name: [first, second][i] })) }
        const dto = path === 'rest' ? createBoxToCreateBox(plainToInstance(RestCreateBoxDto, input) as any) : input
        try {
          await expect(
            f.service.create(dto as any, activeOrg, Context.user(), { createdBy: 'user', onPersist }),
          ).rejects.toBeInstanceOf(BadRequestError)
          expect(f.transfer()).toBeUndefined()
          expect(f.boxRepository.insert).not.toHaveBeenCalled()
          expect(onPersist).not.toHaveBeenCalled()
          expect(f.events.emitAsync).not.toHaveBeenCalled()
        } finally {
          await f.close()
        }
      })

      it('preserves same-name secrets on different hosts when disabled', async () => {
        const f = await fixture(201, false)
        const inline = secrets.map((secret) => ({ ...secret, name: 'key' }))
        const input = { secrets: inline }
        const dto = path === 'rest' ? createBoxToCreateBox(plainToInstance(RestCreateBoxDto, input) as any) : input
        try {
          await f.service.create(dto as any, activeOrg, Context.user())
          expect(f.transfer()).toBeUndefined()
          expect(f.boxRepository.insert.mock.calls[0][0].secrets).toEqual(inline)
        } finally {
          await f.close()
        }
      })
    })

    it('does not transfer a request that fails local lifecycle validation', async () => {
      const f = await fixture()
      try {
        await expect(
          f.service.create({ name: 'invalid', secrets, autoStop: -1 }, activeOrg, Context.user(), {
            createdBy: 'user',
          }),
        ).rejects.toThrow(BadRequestError)
        expect(f.transfer()).toBeUndefined()
        expect(f.boxRepository.insert).not.toHaveBeenCalled()
      } finally {
        await f.close()
      }
    })

    it('keeps plaintext out of failed inserts and emits no creation event', async () => {
      const f = await fixture()
      f.persist.mockRejectedValue(new Error('insert failed'))
      try {
        await expect(
          f.service.create({ name: 'failed-insert', secrets }, activeOrg, Context.user(), { createdBy: 'user' }),
        ).rejects.toThrow('insert failed')
        expect(f.boxRepository.insert.mock.calls[0][0].secrets.every((secret) => !Object.hasOwn(secret, 'value'))).toBe(
          true,
        )
        expect(f.events.emitAsync).not.toHaveBeenCalled()
      } finally {
        await f.close()
      }
    })
  })

  it('persists App ownership on each Box without requiring a volume', async () => {
    const { service, boxRepository, warmPoolService } = makeCreateService({
      imageResolverService: { resolve: jest.fn().mockResolvedValue({ ref: 'ubuntu:22.04', isOrgOwned: false }) },
      redis: { exists: jest.fn().mockResolvedValue(0) },
    })
    for (const name of ['web', 'worker']) {
      await service.create({ image: 'ubuntu:22.04', name }, activeOrg, Context.user(), {
        appEnvironmentId: 'main',
      })
    }
    expect(boxRepository.insert).toHaveBeenCalledTimes(2)
    for (const [box] of boxRepository.insert.mock.calls) {
      expect(box.appId).toBe('app-a')
      expect(box.environmentId).toBe('main')
    }
    expect(warmPoolService.fetchWarmPoolBox).not.toHaveBeenCalled()
  })

  it('leaves standalone Boxes unowned even with App-looking variables and labels', async () => {
    const { service, boxRepository } = makeCreateService()
    await service.create(
      {
        image: 'node:test',
        name: 'scratch',
        env: { BOXLITE_ENV_ID: 'main' },
        labels: { app_id: 'app-a' },
      },
      activeOrg,
      Context.user(),
    )
    const [box] = boxRepository.insert.mock.calls[0]
    expect(box.appId).toBeNull()
    expect(box.environmentId).toBeNull()
  })

  it('refuses an App environment outside the creation organization', async () => {
    const { service, boxRepository } = makeCreateService()
    await expect(
      service.create({ image: 'node:test', name: 'foreign' }, activeOrg, Context.user(), {
        appEnvironmentId: 'missing',
      }),
    ).rejects.toBeInstanceOf(NotFoundException)
    expect(boxRepository.insert).not.toHaveBeenCalled()
  })

  async function appVolumeService() {
    let stored: unknown
    const volumes = new VolumeService(
      {
        findOne: async () => null,
        find: async () => [stored],
        save: async (volume) => (stored = volume),
        manager: {
          query: async (_sql, [_organizationId, environmentId]) => [
            { id: environmentId === 'other-app' ? 'app-b' : 'app-a' },
          ],
        },
      } as never,
      {} as never,
      { assertOrganizationIsNotSuspended: () => undefined } as never,
      { get: () => 'gcs' } as never,
      {} as never,
      {} as never,
    )
    const volume = await volumes.create({ id: 'org-1' } as never, { name: 'app-data' }, Context.user(), {
      appId: 'app-a',
      environmentId: 'main',
    })
    volume.state = VolumeState.READY
    return { volumes, volume }
  }

  it.each(['main', 'staging'])('mounts App-owned volumes for a trusted %s App Box', async (environmentId) => {
    const { volumes, volume } = await appVolumeService()
    const { service, boxRepository } = makeCreateService({ volumeService: volumes })
    await service.create(
      { name: 'app-box', image: 'node:test', volumes: [{ volumeId: volume.name, mountPath: '/data' }] } as never,
      { id: 'org-1' } as never,
      Context.user(),
      { appEnvironmentId: environmentId },
    )
    expect(boxRepository.insert).toHaveBeenCalledWith(
      expect.objectContaining({
        volumes: [{ volumeId: volume.id, mountPath: '/data' }],
      }),
      undefined,
    )
  })

  it('refuses another App at the shared Box creation boundary', async () => {
    const { volumes, volume } = await appVolumeService()
    const { service, boxRepository } = makeCreateService({ volumeService: volumes })
    await expect(
      service.create(
        {
          name: 'foreign-app-box',
          image: 'node:test',
          volumes: [{ volumeId: volume.id, mountPath: '/data' }],
        } as never,
        { id: 'org-1' } as never,
        Context.user(),
        { appEnvironmentId: 'other-app' },
      ),
    ).rejects.toBeInstanceOf(ForbiddenException)
    expect(boxRepository.insert).not.toHaveBeenCalled()
  })

  it('the public REST route cannot claim App ownership through process variables', async () => {
    const { volumes, volume } = await appVolumeService()
    const { service, boxRepository } = makeCreateService({ volumeService: volumes })
    const builder = Test.createTestingModule({
      controllers: [BoxliteBoxController],
      providers: [
        { provide: BoxService, useValue: service },
        { provide: BoxStateWaiterService, useValue: {} },
        { provide: CheckpointRecoverService, useValue: {} },
        { provide: BoxUsageService, useValue: {} },
        { provide: CommerceBoxLimitService, useValue: { resolveMaxCreatedBoxes: async () => undefined } },
      ],
    })
    builder.overrideGuard(CombinedAuthGuard).useValue({
      canActivate: (context) => {
        context.switchToHttp().getRequest().user = {
          userId: 'owner',
          role: 'admin',
          organizationId: 'org-1',
          organization: { id: 'org-1' },
          organizationUser: { role: 'owner' },
          apiKey: { permissions: Object.values(OrganizationResourcePermission) },
        }
        return true
      },
    })
    builder.overrideGuard(OrganizationResourceActionGuard).useValue({ canActivate: () => true })
    builder.overrideGuard(AuthenticatedRateLimitGuard).useValue({ canActivate: () => true })
    const application = (await builder.compile()).createNestApplication()
    try {
      await application.listen(0, '127.0.0.1')
      const response = await fetch(`${await application.getUrl()}/v1/boxes`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: 'standalone',
          image: 'node:test',
          env: { BOXLITE_ENV_ID: 'main' },
          volumes: [{ managed_volume: volume.id, guest_path: '/data' }],
        }),
      })
      expect(response.status).toBe(403)
      expect((await response.json()).message).toContain('belongs to App')
      expect(boxRepository.insert).not.toHaveBeenCalled()
    } finally {
      await application.close()
    }
  })

  it('caller-supplied labels grant no App volume access at the shared creation boundary', async () => {
    const { volumes, volume } = await appVolumeService()
    const { service, boxRepository } = makeCreateService({ volumeService: volumes })
    await expect(
      service.create(
        {
          name: 'standalone',
          image: 'node:test',
          labels: { 'boxlite.io/managed-by': 'cloud-app', app_id: 'app-a' },
          volumes: [{ volumeId: volume.id, mountPath: '/data' }],
        } as never,
        { id: 'org-1' } as never,
        Context.user(),
      ),
    ).rejects.toBeInstanceOf(ForbiddenException)
    expect(boxRepository.insert).not.toHaveBeenCalled()
  })

  /**
   * Two collaborators now stand between the request and the box: admission
   * decides whether this image may be used at all, and the resolver decides
   * which ref a runner is handed. What is asserted here is the seam — both are
   * asked, and the box records the resolver's answer rather than what the
   * caller typed. Which ref the resolver picks is its own specification's job.
   */
  describe('organization nesting default', () => {
    it.each([null, new Error('policy database unavailable')])(
      'rejects creation when policy lookup returns %p',
      async (failure) => {
        const organizationRepository = {
          findOne: failure instanceof Error ? jest.fn().mockRejectedValue(failure) : jest.fn().mockResolvedValue(null),
        }
        const organizationService = Object.create(OrganizationService.prototype)
        Object.assign(organizationService, { organizationRepository, assertOrganizationIsNotSuspended: jest.fn() })
        const { service, boxRepository } = makeCreateService({ organizationService })
        await expect(
          service.create({ name: 'missing-policy', image: 'alpine' } as any, { id: 'org-1' } as any, Context.user()),
        ).rejects.toThrow(failure instanceof Error ? failure : /Organization.*not found/)
        expect(boxRepository.insert).not.toHaveBeenCalled()
      },
    )

    it.each([true, false])(
      'ignores stale organization policy when creating with current policy=%s',
      async (enabled) => {
        const organization = { id: 'org-1', nestedVirtualizationEnabled: !enabled }
        const organizationRepository = {
          findOne: jest.fn().mockResolvedValue({ id: organization.id, nestedVirtualizationEnabled: enabled }),
        }
        const organizationService = Object.create(OrganizationService.prototype)
        Object.assign(organizationService, { organizationRepository, assertOrganizationIsNotSuspended: jest.fn() })
        const { service, boxRepository, warmPoolService } = makeCreateService({
          organizationService,
          runnerService: { getRandomAvailableRunner: jest.fn().mockResolvedValue({ id: 'runner-1', apiVersion: '0' }) },
          runnerAdapterFactory: {
            create: jest
              .fn()
              .mockResolvedValue({ runnerInfo: jest.fn().mockResolvedValue({ nestedVirtualizationEnabled: true }) }),
          },
          configService: { getOrThrow: () => 1 },
        })
        ;(service as any).imageResolverService.resolve.mockResolvedValue({ ref: 'curated', isOrgOwned: false })
        ;(service as any).redis.exists.mockResolvedValue(0)

        const box = await service.create(
          { name: 'fresh-policy', image: 'curated' } as any,
          organization as any,
          Context.user(),
        )

        expect(box).not.toHaveProperty('nestedVirtualization')
        expect(boxRepository.insert.mock.calls[0][0]).not.toHaveProperty('nestedVirtualization')
        expect(warmPoolService.fetchWarmPoolBox).toHaveBeenCalledTimes(enabled ? 0 : 1)
        expect(organization.nestedVirtualizationEnabled).toBe(!enabled)
        expect(organizationRepository.findOne).toHaveBeenCalledWith({
          where: { id: organization.id },
          select: { id: true, nestedVirtualizationEnabled: true },
          cache: false,
        })
      },
    )

    function fixture() {
      return makeCreateService({
        organizationService: {
          assertOrganizationIsNotSuspended: jest.fn(),
          isNestedVirtualizationEnabled: jest.fn().mockResolvedValue(true),
        },
      })
    }
    it('bypasses an ordinary warm box for an allowlisted organization', async () => {
      const { service, warmPoolService } = fixture()
      ;(service as any).imageResolverService.resolve.mockResolvedValue({ ref: 'curated', isOrgOwned: false })
      ;(service as any).redis.exists.mockResolvedValue(0)
      await service.create(
        { name: 'fresh', image: 'curated' } as any,
        { id: 'org-1', nestedVirtualizationEnabled: true } as any,
        Context.user(),
      )
      expect(warmPoolService.fetchWarmPoolBox).not.toHaveBeenCalled()
    })
  })

  it('stores the ref the resolver returned, not the selector the caller sent', async () => {
    const { service, boxRepository } = makeCreateService()

    await service.create(
      { name: 'tenant-box', image: 'quay.io/acme/app:v1' } as any,
      { id: 'org-1' } as any,
      Context.user(),
    )

    expect((service as any).imageAdmissionService.assert).toHaveBeenCalledWith(
      expect.objectContaining({ id: 'org-1' }),
      'quay.io/acme/app:v1',
    )
    expect((service as any).imageResolverService.resolve).toHaveBeenCalledWith(
      expect.objectContaining({ id: 'org-1' }),
      'quay.io/acme/app:v1',
    )
    expect(boxRepository.insert).toHaveBeenCalledWith(
      expect.objectContaining({ image: 'quay.io/acme/app@sha256:resolved' }),
      undefined,
    )
  })

  it('persists the resolved volume id when a ready volume is selected by name', async () => {
    const volume = Object.assign(new Volume(), {
      id: '09f81aef-69a3-488b-b872-e193831549f3',
      name: 'shared-data',
      state: VolumeState.READY,
    })
    const validateVolumes = jest.fn().mockResolvedValue(new Map([['shared-data', volume]]))
    const { service, boxRepository } = makeCreateService({ volumeService: { validateVolumes } })

    await service.create(
      {
        name: 'volume-box',
        image: 'quay.io/acme/app:v1',
        volumes: [{ volumeId: 'shared-data', mountPath: '/data' }],
      } as any,
      { id: 'org-1' } as any,
      Context.user(),
    )

    expect(validateVolumes).toHaveBeenCalledWith('org-1', ['shared-data'], undefined)
    expect(boxRepository.insert).toHaveBeenCalledWith(
      expect.objectContaining({ volumes: [{ volumeId: volume.id, mountPath: '/data' }] }),
      undefined,
    )
  })

  /**
   * The one path every existing caller takes, and the only one asserted through
   * the real resolver: a mocked one would make this a test of the mock. The
   * repository throws, so a curated selector reaching the database fails here
   * rather than merely costing a query.
   */
  it('still resolves a curated selector to its operator-configured ref', async () => {
    const repository = {
      createQueryBuilder: () => {
        throw new Error('a curated selector must not query the catalog')
      },
    } as unknown as Repository<ImageVersion>
    const { service, boxRepository } = makeCreateService({
      imageResolverService: new ImageResolverService(repository, {
        routesThroughProxy: () => {
          throw new Error('a curated selector must not ask about registered logins')
        },
      } as unknown as RegistryCredentialService),
    })

    await service.create({ name: 'curated-box', image: 'python' } as any, { id: 'org-1' } as any, Context.user())

    expect(boxRepository.insert).toHaveBeenCalledWith(
      expect.objectContaining({ image: expect.stringContaining('boxlite-agent-python') }),
      undefined,
    )
  })

  /**
   * The pool holds boxes created with no organization, so an image one
   * organization owns must not be served from it. Asserted on the collaborators
   * rather than on the returned box: a fresh box is what a warm miss produces
   * too, so the outcome alone cannot tell the two apart.
   *
   * The Redis key matters on its own. `warm-pool:skip:<image>` is named after
   * the image, so reaching that line with a tenant-supplied ref would let a
   * caller decide a key's name.
   */
  it('neither consults the warm pool nor names a skip key for an org image', async () => {
    const { service, warmPoolService } = makeCreateService()

    await service.create(
      { name: 'tenant-box', image: 'quay.io/acme/app:v1' } as any,
      { id: 'org-1' } as any,
      Context.user(),
    )

    expect((service as any).redis.exists).not.toHaveBeenCalled()
    expect(warmPoolService.fetchWarmPoolBox).not.toHaveBeenCalled()
  })

  it('still consults the warm pool for a curated image', async () => {
    const { service, warmPoolService } = makeCreateService({
      imageResolverService: {
        resolve: jest
          .fn()
          .mockResolvedValue({ ref: 'ghcr.io/boxlite-ai/boxlite-agent-base:v0.1.0', isOrgOwned: false }),
      },
      // No skip key: the default fixture has one, which would keep the pool
      // out of this test for a reason that has nothing to do with the image.
      redis: { exists: jest.fn().mockResolvedValue(0) },
    })

    await service.create({ name: 'curated-box', image: 'base' } as any, { id: 'org-1' } as any, Context.user())

    expect((service as any).redis.exists).toHaveBeenCalled()
    expect(warmPoolService.fetchWarmPoolBox).toHaveBeenCalled()
  })

  /**
   * The other side of the same rule. A pool row is filled by a background
   * top-up, not by a request, so nothing upstream of here has checked its
   * image — and the box it creates belongs to no organization until one claims
   * it.
   */
  it('refuses to fill a warm pool row that names an image an organization owns', async () => {
    const { service, boxRepository } = makeCreateService()

    await expect(
      service.createForWarmPool({ id: 'pool-7', image: 'quay.io/acme/app:v1', target: 'region-1', cpu: 1 } as any),
    ).rejects.toThrow(/pool-7/)
    expect(boxRepository.insert).not.toHaveBeenCalled()
  })

  it('fills a warm pool row that names a curated image', async () => {
    const { service, boxRepository } = makeCreateService()

    await service.createForWarmPool({
      id: 'pool-8',
      image: 'ghcr.io/boxlite-ai/boxlite-agent-base:v0.1.0',
      target: 'region-1',
      class: 'small',
      cpu: 2,
      mem: 4,
      disk: 10,
      gpu: 0,
      osUser: 'boxlite',
      env: {},
    } as any)

    expect(boxRepository.insert).toHaveBeenCalled()
  })

  it('asks admission before the resolver, and spends the budget on its answer', async () => {
    const { service } = makeCreateService()
    const order: string[] = []
    const resolved = { ref: 'quay.io/acme/app@sha256:resolved', isOrgOwned: true }
    ;(service as any).imageAdmissionService.assert.mockImplementation(async () => void order.push('admission'))
    ;(service as any).imageResolverService.resolve.mockImplementation(async () => {
      order.push('resolver')
      return resolved
    })
    ;(service as any).imageAdmissionService.spendColdPullBudget.mockImplementation(
      async () => void order.push('budget'),
    )

    await service.create(
      { name: 'ordered-box', image: 'quay.io/acme/app:v1' } as any,
      { id: 'org-1' } as any,
      Context.user(),
    )

    // A refused image must not reach a catalog query.
    expect(order).toEqual(['admission', 'resolver', 'budget'])
    expect((service as any).imageAdmissionService.spendColdPullBudget).toHaveBeenCalledWith(
      expect.objectContaining({ id: 'org-1' }),
      resolved,
    )
  })

  /**
   * A cold pull is a ref the catalog could not answer. A hit is handed out by
   * digest, a build this deployment already pulled and booted, so charging it
   * too capped how fast any organization could create boxes from its own images.
   * Driven through the real admission service: which creates spend the budget
   * is decided by the seam between it and the resolver, not by either alone.
   */
  describe('cold-pull budget', () => {
    function withRealAdmission(resolved: object, overrides: Record<string, unknown> = {}) {
      const redis = { eval: jest.fn().mockResolvedValue([1, 'gen-1', 60000]) }
      const images = { exists: jest.fn().mockResolvedValue(true), count: jest.fn().mockResolvedValue(0) }
      const { service, boxRepository } = makeCreateService({
        imageAdmissionService: new ImageAdmissionService(
          redis as unknown as Redis,
          images as unknown as Repository<Image>,
          { routesThroughProxy: jest.fn().mockResolvedValue(false) } as unknown as RegistryCredentialService,
        ),
        imageResolverService: { resolve: jest.fn().mockResolvedValue(resolved) },
        ...overrides,
      })
      return { service, redis, boxRepository }
    }

    let allowlistBefore: string | undefined
    beforeEach(() => {
      allowlistBefore = process.env.BOXLITE_IMAGE_REGISTRY_ALLOWLIST
      process.env.BOXLITE_IMAGE_REGISTRY_ALLOWLIST = 'quay.io'
    })

    afterEach(() => {
      if (allowlistBefore === undefined) {
        delete process.env.BOXLITE_IMAGE_REGISTRY_ALLOWLIST
      } else {
        process.env.BOXLITE_IMAGE_REGISTRY_ALLOWLIST = allowlistBefore
      }
    })

    it('spends none on a ref the catalog already pinned', async () => {
      const pinned = { ref: `quay.io/acme/app@sha256:${'a'.repeat(64)}`, isOrgOwned: true, imageId: 'image-1' }
      const { service, redis } = withRealAdmission(pinned)

      await service.create(
        { name: 'pinned-box', image: 'quay.io/acme/app:v1' } as any,
        { id: 'org-1' } as any,
        Context.user(),
      )

      expect(redis.eval).not.toHaveBeenCalled()
    })

    /**
     * Nothing returns a pull slot: the counter has no decrement, because the
     * API never learns a pull ended. Spending one on a create that was going to
     * be refused would charge an organization for a box it cannot have.
     */
    it('spends none on a create the image limit refuses', async () => {
      const { service, redis } = withRealAdmission({ ref: 'quay.io/acme/app:v1', isOrgOwned: true })
      const images = (service as any).imageAdmissionService.imageRepository
      images.exists.mockResolvedValue(false)
      images.count.mockResolvedValue(20)

      await expect(
        service.create(
          { name: 'over-box', image: 'quay.io/acme/app:v1' } as any,
          { id: 'org-1', imageCountLimit: 20 } as any,
          Context.user(),
        ),
      ).rejects.toThrow(/limit of 20 images/)

      expect(redis.eval).not.toHaveBeenCalled()
    })

    /** A volume the create names but cannot have refuses it after resolution. */
    it('spends none on a create whose volume is refused', async () => {
      const { service, redis } = withRealAdmission(
        { ref: 'quay.io/acme/app:v1', isOrgOwned: true },
        { volumeService: { validateVolumes: jest.fn().mockRejectedValue(new Error('no such volume')) } },
      )

      await expect(
        service.create(
          {
            name: 'volume-box',
            image: 'quay.io/acme/app:v1',
            volumes: [{ volumeId: 'missing', mountPath: '/data' }],
          } as any,
          { id: 'org-1' } as any,
          Context.user(),
        ),
      ).rejects.toThrow(/no such volume/)

      expect(redis.eval).not.toHaveBeenCalled()
    })

    it.each([
      ['a negative auto-stop interval', { autoStop: -5 }],
      ['a network allow list that is not one', { outboundAllowNet: ['bad host!'] }],
    ])('spends none on a create refused for %s', async (_reason, input) => {
      const { service, redis } = withRealAdmission({ ref: 'quay.io/acme/app:v1', isOrgOwned: true })

      await expect(
        service.create(
          { name: 'refused-box', image: 'quay.io/acme/app:v1', ...input } as any,
          { id: 'org-1' } as any,
          Context.user(),
        ),
      ).rejects.toThrow(BadRequestError)

      expect(redis.eval).not.toHaveBeenCalled()
    })

    it('spends none on a create no runner can take', async () => {
      const { service, redis } = withRealAdmission(
        { ref: 'quay.io/acme/app:v1', isOrgOwned: true },
        { runnerService: { getRandomAvailableRunner: jest.fn().mockRejectedValue(new Error('no runner')) } },
      )

      await expect(
        service.create(
          { name: 'unplaced-box', image: 'quay.io/acme/app:v1' } as any,
          { id: 'org-1' } as any,
          Context.user(),
        ),
      ).rejects.toThrow(/no runner/)

      expect(redis.eval).not.toHaveBeenCalled()
    })

    it('inserts no box when the budget refuses the create', async () => {
      const { service, redis, boxRepository } = withRealAdmission({ ref: 'quay.io/acme/app:v1', isOrgOwned: true })
      redis.eval.mockResolvedValue([7, 'gen-1', 30000])

      await expect(
        service.create(
          { name: 'over-budget-box', image: 'quay.io/acme/app:v1' } as any,
          { id: 'org-1' } as any,
          Context.user(),
        ),
      ).rejects.toThrow(/Too many image pulls/)

      expect(boxRepository.insert).not.toHaveBeenCalled()
    })

    it('refunds the charged generation when the box limit refuses insertion', async () => {
      const { service, redis, boxRepository } = withRealAdmission({ ref: 'quay.io/acme/app:v1', isOrgOwned: true })
      redis.eval.mockResolvedValueOnce([1, 'gen-7', 60000]).mockResolvedValueOnce(0)
      boxRepository.insert.mockRejectedValue(new BoxCreationLimitExceededError(3, 3))

      await expect(
        service.create(
          plainToInstance(CreateBoxDto, { name: 'over-limit-box', image: 'quay.io/acme/app:v1' }),
          plainToInstance(Organization, { id: 'org-1' }),
          Context.user(),
        ),
      ).rejects.toThrow(BoxCreationLimitExceededError)

      expect(redis.eval.mock.calls[1].slice(1)).toEqual([
        2,
        'image:coldpull:org-1',
        'image:coldpull:org-1:gen',
        'gen-7',
        1,
      ])
    })

    it('does not refund when spending fails before returning a ticket', async () => {
      const { service, redis, boxRepository } = withRealAdmission({ ref: 'quay.io/acme/app:v1', isOrgOwned: true })
      redis.eval.mockRejectedValueOnce(new Error('connection dropped'))

      await expect(
        service.create(
          plainToInstance(CreateBoxDto, { name: 'broken-pipe-box', image: 'quay.io/acme/app:v1' }),
          plainToInstance(Organization, { id: 'org-1' }),
          Context.user(),
        ),
      ).rejects.toThrow('connection dropped')
      expect(redis.eval).toHaveBeenCalledTimes(1)
      expect(boxRepository.insert).not.toHaveBeenCalled()
    })

    it('spends one on a ref the catalog has not seen', async () => {
      const { service, redis } = withRealAdmission({ ref: 'quay.io/acme/app:v1', isOrgOwned: true })

      await service.create(
        { name: 'first-box', image: 'quay.io/acme/app:v1' } as any,
        { id: 'org-1' } as any,
        Context.user(),
      )

      expect(redis.eval).toHaveBeenCalledTimes(1)
    })
  })

  it.each([
    [{ outboundEnabled: false }, { boxLimitedNetworkEgress: false }],
    [{}, { boxLimitedNetworkEgress: true }],
  ])('rejects disabled outbound rules before creating a box: %j / %j', async (request, org) => {
    const { service, boxRepository, warmPoolService } = makeCreateService()
    await expect(
      service.create(
        { name: 'invalid-network', image: 'base', outboundAllowNet: ['example.com'], ...request } as any,
        { id: 'org-1', ...org } as any,
        Context.user(),
      ),
    ).rejects.toThrow('disabled outbound cannot include allow_net')
    expect(boxRepository.insert).not.toHaveBeenCalled()
    expect(warmPoolService.fetchWarmPoolBox).not.toHaveBeenCalled()
    expect((service as any).imageAdmissionService.assert).not.toHaveBeenCalled()
  })

  it.each([
    [{ outboundEnabled: false }, { boxLimitedNetworkEgress: false }, { outboundEnabled: false }],
    [{ outboundAllowNet: ['10.0.0.0/8'] }, { boxLimitedNetworkEgress: false }, { outboundAllowNet: ['10.0.0.0/8'] }],
    [{ outboundEnabled: true }, { boxLimitedNetworkEgress: true }, { outboundEnabled: true }],
    [{}, { boxLimitedNetworkEgress: true }, { outboundEnabled: false }],
  ])(
    'creates a fresh box instead of claiming a warm box when network policy is required',
    async (request, org, expected) => {
      const { service, boxRepository, warmPoolService } = makeCreateService()
      ;(service as any).redis.exists.mockResolvedValue(0)

      await service.create(
        { name: 'restricted-box', image: 'base', ...request } as any,
        { id: 'org-1', ...org } as any,
        Context.user(),
      )

      expect(warmPoolService.fetchWarmPoolBox).not.toHaveBeenCalled()
      expect(boxRepository.insert).toHaveBeenCalledWith(expect.objectContaining(expected), undefined)
    },
  )

  it.each([
    [undefined, false],
    [true, true],
  ])('persists inbound access %s as %s on a fresh box', async (requested, expected) => {
    const { service, boxRepository } = makeCreateService()

    await service.create(
      { name: 'fresh-box', inboundEnabled: requested } as any,
      { id: 'org-1' } as any,
      Context.user(),
    )

    expect(boxRepository.insert).toHaveBeenCalledWith(
      expect.objectContaining({ inboundEnabled: expected, outboundEnabled: true }),
      undefined,
    )
  })

  it.each([
    ['network omitted', undefined, false],
    ['legacy flat network', { mode: 'enabled' }, false],
    ['nested outbound only', { outbound: { mode: 'enabled' } }, false],
    ['inbound enabled', { inbound: { mode: 'enabled' } }, true],
    ['inbound disabled', { inbound: { mode: 'disabled' } }, false],
  ])('persists REST %s with inbound enabled %s', async (_label, network, expected) => {
    const { service, boxRepository } = makeCreateService()
    const restDto = plainToInstance(RestCreateBoxDto, { name: 'rest-box', image: 'base', network })

    await service.create(createBoxToCreateBox(restDto), { id: 'org-1' } as any, Context.user())

    expect(boxRepository.insert).toHaveBeenCalledWith(expect.objectContaining({ inboundEnabled: expected }), undefined)
  })

  // The whole outbound policy crosses the REST mapper and the service: the
  // mode flips polarity and the allowlist is split into entries.
  it('persists a REST outbound allowlist as policy columns', async () => {
    const { service, boxRepository } = makeCreateService()
    const restDto = plainToInstance(RestCreateBoxDto, {
      name: 'rest-box',
      image: 'base',
      network: { outbound: { mode: 'enabled', allow_net: ['api.openai.com', ' 10.0.0.0/8 '] } },
    })

    await service.create(createBoxToCreateBox(restDto), { id: 'org-1' } as any, Context.user())

    expect(boxRepository.insert).toHaveBeenCalledWith(
      expect.objectContaining({ outboundEnabled: true, outboundAllowNet: ['api.openai.com', '10.0.0.0/8'] }),
      undefined,
    )
  })

  it('persists secrets on a freshly created box', async () => {
    const { service, boxRepository } = makeCreateService()

    await service.create(
      {
        name: 'secret-box',
        image: 'base',
        secrets: [
          { name: 'openai', value: 'sk-test', hosts: ['api.openai.com'], headers: { Authorization: 'Bearer {value}' } },
        ],
      } as any,
      { id: 'org-1' } as any,
      Context.user(),
    )

    expect(boxRepository.insert).toHaveBeenCalledWith(
      expect.objectContaining({
        secrets: [
          { name: 'openai', value: 'sk-test', hosts: ['api.openai.com'], headers: { Authorization: 'Bearer {value}' } },
        ],
      }),
      undefined,
    )
  })

  describe.each(['direct', 'rest'])('required headers through %s create', (path) => {
    it.each([undefined, null, {}])('rejects absent headers %j before persistence', async (headers) => {
      const { service, boxRepository } = makeCreateService()
      const input = { image: 'base', secrets: [{ name: 'x', value: 'token', hosts: ['api.test.com'], headers }] }
      const dto = path === 'rest' ? createBoxToCreateBox(plainToInstance(RestCreateBoxDto, input) as any) : input
      await expect(service.create(dto as any, { id: 'org-1' } as any, Context.user())).rejects.toThrow(
        'secret "x" has no headers; recreate the box with headers',
      )
      expect(boxRepository.insert).not.toHaveBeenCalled()
    })
  })

  describe.each(['direct', 'rest'])('secret headers through %s create', (path) => {
    it.each([
      {},
      '',
      [],
      { 'Bad Header': '{value}' },
      { 'X-Key': '' },
      { 'X-Key': '{value}{value}' },
      { 'X-Key': '{other}{value}' },
      { 'X-Key': '{value}\r\n' },
      { 'X-Key': '{value}\u007f' },
      { 'X-Key': '{value}', 'x-key': '{value}' },
    ])('rejects invalid templates %j before persistence', async (headers) => {
      const { service, boxRepository } = makeCreateService()
      const input = { image: 'base', secrets: [{ name: 'key', value: 'token', hosts: ['api.example.com'], headers }] }
      const dto = path === 'rest' ? createBoxToCreateBox(plainToInstance(RestCreateBoxDto, input) as any) : input
      await expect(service.create(dto as any, { id: 'org-1' } as any, Context.user())).rejects.toBeInstanceOf(
        BadRequestError,
      )
      expect(boxRepository.insert).not.toHaveBeenCalled()
    })

    it.each(['\u0000', '\u0001', '\r', '\n', '\u007f'])('rejects control bytes in the value %j', async (control) => {
      const { service, boxRepository } = makeCreateService()
      const input = {
        image: 'base',
        secrets: [
          {
            name: 'key',
            value: `token${control}`,
            hosts: ['api.example.com'],
            headers: { Authorization: 'Bearer {value}' },
          },
        ],
      }
      const dto = path === 'rest' ? createBoxToCreateBox(plainToInstance(RestCreateBoxDto, input) as any) : input
      await expect(service.create(dto as any, { id: 'org-1' } as any, Context.user())).rejects.toBeInstanceOf(
        BadRequestError,
      )
      expect(boxRepository.insert).not.toHaveBeenCalled()
    })

    it('persists multiple templates without interpreting the secret value', async () => {
      const { service, boxRepository } = makeCreateService()
      const secrets = [
        {
          name: 'key',
          value: 'token {value}\t',
          hosts: ['api.example.com', 'API.example.com'],
          headers: { Authorization: 'Bot {value}', 'X-Key': '\t{value} ' },
        },
      ]
      const input = { image: 'base', secrets }
      const dto = path === 'rest' ? createBoxToCreateBox(plainToInstance(RestCreateBoxDto, input) as any) : input
      await service.create(dto as any, { id: 'org-1' } as any, Context.user())
      expect(boxRepository.insert).toHaveBeenCalledWith(expect.objectContaining({ secrets }), undefined)
    })
  })

  it.each(['direct', 'rest'])('rejects a forbidden secret header on the %s create path', async (path) => {
    const { service, boxRepository } = makeCreateService()
    const input = {
      name: 'secret-box',
      image: 'base',
      secrets: [
        { name: 'key', value: 'test-value', hosts: ['api.example.com'], headers: { 'Proxy-Connection': '{value}' } },
      ],
    }
    const dto = path === 'rest' ? createBoxToCreateBox(plainToInstance(RestCreateBoxDto, input) as any) : input

    let error: unknown
    try {
      await service.create(dto as any, { id: 'org-1' } as any, Context.user())
    } catch (caught) {
      error = caught
    }
    expect(error).toBeInstanceOf(BadRequestError)
    expect(String(error)).not.toContain('test-value')
    expect(boxRepository.insert).not.toHaveBeenCalled()
  })

  it.each([
    'Host',
    'Connection',
    'Proxy-Connection',
    'proxy-authenticate',
    'Proxy-Authorization',
    'Keep-Alive',
    'TE',
    'Trailer',
    'Upgrade',
    'Content-Length',
    'Transfer-Encoding',
  ])('rejects forbidden header %s', async (header) => {
    const { service } = makeCreateService()
    await expect(
      service.create(
        {
          image: 'base',
          secrets: [{ name: 'key', value: 'test-value', hosts: ['api.example.com'], headers: { [header]: '{value}' } }],
        } as any,
        { id: 'org-1' } as any,
        Context.user(),
      ),
    ).rejects.toBeInstanceOf(BadRequestError)
  })

  it.each([
    [
      { name: 'first', value: 'one', hosts: ['api.example.com'], headers: { 'x-api-key': '{value}' } },
      { name: 'second', value: 'two', hosts: ['api.example.com'], headers: { Authorization: '{value}' } },
    ],
    [
      {
        name: 'first',
        value: 'one',
        hosts: ['api.example.com', 'API.example.com'],
        headers: { 'x-api-key': '{value}' },
      },
    ],
  ])('allows distinct headers and repeated hosts within one secret', async (...secrets) => {
    const { service, boxRepository } = makeCreateService()
    await service.create({ image: 'base', secrets } as any, { id: 'org-1' } as any, Context.user())
    expect(boxRepository.insert).toHaveBeenCalled()
  })

  it.each([
    [
      'bad token',
      [{ name: 'key', value: 'test-value', hosts: ['api.example.com'], headers: { 'bad header': '{value}' } }],
    ],
    ['empty header', [{ name: 'key', value: 'test-value', hosts: ['api.example.com'], headers: { '': '{value}' } }]],
    [
      'duplicate host and header',
      [
        { name: 'first', value: 'test-value', hosts: ['API.example.com'], headers: { 'X-API-Key': '{value}' } },
        { name: 'second', value: 'other-value', hosts: ['api.example.com'], headers: { 'x-api-key': '{value}' } },
      ],
    ],
  ])('rejects %s in secret headers', async (_case, secrets) => {
    const { service } = makeCreateService()
    await expect(
      service.create({ name: 'secret-box', image: 'base', secrets } as any, { id: 'org-1' } as any, Context.user()),
    ).rejects.toBeInstanceOf(BadRequestError)
  })

  it.each([
    [undefined, false],
    [false, false],
    [true, true],
  ])('persists REST guest privilege %s as %s', async (privileged, expected) => {
    const { service, boxRepository } = makeCreateService()
    const dto = plainToInstance(RestCreateBoxDto, {
      name: 'docker-box',
      image: 'docker:27.5.1-dind',
      advanced: privileged === undefined ? undefined : { privileged },
    })

    await service.create(createBoxToCreateBox(dto), { id: 'org-1' } as any, Context.user())

    expect(boxRepository.insert).toHaveBeenCalledWith(expect.objectContaining({ privileged: expected }), undefined)
  })

  it('creates a fresh privileged guest when an ordinary warm box is available', async () => {
    const { service, boxRepository, warmPoolService } = makeCreateService({
      redis: { exists: jest.fn().mockResolvedValue(0) },
      imageResolverService: { resolve: jest.fn().mockResolvedValue({ ref: 'base', isOrgOwned: false }) },
    })
    warmPoolService.fetchWarmPoolBox.mockResolvedValue({ id: 'warm-box' } as any)

    await service.create(
      { name: 'docker-box', image: 'base', privileged: true } as any,
      { id: 'org-1' } as any,
      Context.user(),
    )

    expect(warmPoolService.fetchWarmPoolBox).not.toHaveBeenCalled()
    expect(boxRepository.insert).toHaveBeenCalledWith(expect.objectContaining({ privileged: true }), undefined)
  })

  it('creates a fresh box instead of claiming a warm box when secrets are present', async () => {
    const { service, boxRepository, warmPoolService } = makeCreateService()
    // Default exists=1 would skip the warm-pool branch outright; clear it so
    // the assertion below actually guards the secrets needsFreshBox path.
    ;(service as any).redis.exists.mockResolvedValue(0)

    await service.create(
      {
        name: 'secret-box',
        image: 'base',
        secrets: [
          { name: 'openai', value: 'sk-test', hosts: ['api.openai.com'], headers: { Authorization: 'Bearer {value}' } },
        ],
      } as any,
      { id: 'org-1' } as any,
      Context.user(),
    )

    expect(warmPoolService.fetchWarmPoolBox).not.toHaveBeenCalled()
    expect(boxRepository.insert).toHaveBeenCalled()
  })

  it.each([
    [undefined, false],
    [true, true],
  ])('persists inbound access %s as %s on an assigned warm-pool box', async (requested, expected) => {
    const warmPoolBox = { id: 'warm-box', runnerId: 'runner-1', name: 'warm-box' } as any
    const update = jest.fn().mockResolvedValue(warmPoolBox)
    const service = Object.create(BoxService.prototype) as BoxService
    Object.assign(service as any, {
      boxRepository: { update },
      boxLookupCacheInvalidationService: { invalidateOrgId: jest.fn() },
      eventEmitter: { emit: jest.fn() },
      toBoxDto: jest.fn((box) => box),
    })

    await (service as any).assignWarmPoolBox(
      warmPoolBox,
      { name: 'assigned-box', inboundEnabled: requested },
      { id: 'org-1' },
      {},
      {},
    )

    expect(update).toHaveBeenCalledWith(
      'warm-box',
      expect.objectContaining({ updateData: expect.objectContaining({ inboundEnabled: expected }) }),
    )
  })
})

// Assignment is what turns a chosen runner into a committed box row. The only
// seams it crosses are the candidate query and the insert — no transaction of
// its own, and no lock on the runner row.
describe('BoxService runner assignment', () => {
  function makeAssignment() {
    const runner = { id: 'runner-1', draining: false, state: RunnerState.READY }
    const boxRepository = { insert: jest.fn(async (box: any) => box) } as any
    const runnerService = { getRandomAvailableRunner: jest.fn().mockResolvedValue(runner) }
    // Wired even though assignment no longer reaches for it: a fixture that
    // omits a collaborator the code under test could use cannot tell an
    // unlocked assignment from a mis-assembled one.
    const dataSource = { transaction: jest.fn() }
    const service = Object.create(BoxService.prototype) as BoxService
    Object.assign(service as any, {
      logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },
      runnerService,
      dataSource,
      boxRepository,
    })

    // Drives the private assignment directly rather than through create(),
    // whose quota / region / warm-pool preamble only obscures it.
    const assign = (name = 'box-1', privileged = false) => {
      const box = { id: name, runnerId: undefined as string | undefined, privileged }
      return (service as any).persistOnAvailableRunner(box, { regions: ['us'] }, () => boxRepository.insert(box))
    }
    return { assign, boxRepository, runnerService, dataSource }
  }

  it('requires runner privilege support when assigning a privileged Box', async () => {
    const { assign, runnerService } = makeAssignment()

    await assign('docker-box', true)

    expect(runnerService.getRandomAvailableRunner).toHaveBeenCalledWith({
      regions: ['us'],
      requiresPrivileged: true,
    })
  })

  it('commits the box on the chosen runner without locking its row', async () => {
    const { assign, boxRepository, dataSource } = makeAssignment()

    const box = await assign()

    expect(box.runnerId).toBe('runner-1')
    expect(boxRepository.insert).toHaveBeenCalledWith(expect.objectContaining({ runnerId: 'runner-1' }))
    // No transaction of its own means no row lock on the runner: a drain never
    // waits for this insert, and this insert never waits for a drain — so it can
    // land on a runner that goes draining in between, which is the accepted
    // trade.
    expect(dataSource.transaction).not.toHaveBeenCalled()
  })

  it('leaves an empty candidate set as the 400 it already is', async () => {
    const { assign, boxRepository, runnerService } = makeAssignment()
    runnerService.getRandomAvailableRunner.mockRejectedValue(new BadRequestError('No available runners'))

    // Nothing in that region and class can take this box. With no contention
    // left to mistake it for, there is no retryable reading of this failure.
    await expect(assign()).rejects.toMatchObject({ status: 400, message: 'No available runners' })
    expect(boxRepository.insert).not.toHaveBeenCalled()
  })
})

// A box's persisted volume entry must carry the resolved entity id — and,
// for a filestore volume, the entity's instance, which is what the runner's
// mount dispatch (create now, start-after-reboot metadata later) hands over.
// Persisting the caller's selector or dropping the instance would leave the
// runner unable to mount the volume.
describe('BoxService volume reference resolution', () => {
  function makeService(overrides: Record<string, unknown> = {}) {
    const boxRepository = { insert: jest.fn(async (box: any) => box) } as any
    const service = Object.create(BoxService.prototype) as BoxService
    Object.assign(service as any, {
      getValidatedOrDefaultRegion: jest.fn().mockResolvedValue({ id: 'region-1' }),
      getValidatedOrDefaultClass: jest.fn().mockReturnValue('small'),
      organizationService: {
        assertOrganizationIsNotSuspended: jest.fn(),
        isNestedVirtualizationEnabled: jest.fn().mockResolvedValue(false),
      },
      organizationBoxLimits: { resolve: jest.fn(async (organization) => organization) },
      redis: { exists: jest.fn().mockResolvedValue(1) },
      logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },
      warmPoolService: { fetchWarmPoolBox: jest.fn().mockResolvedValue(undefined) },
      runnerService: {
        getRandomAvailableRunner: jest
          .fn()
          .mockResolvedValue({ id: 'runner-1', draining: false, state: RunnerState.READY }),
      },
      boxRepository,
      eventEmitter: { emitAsync: jest.fn().mockResolvedValue(undefined) },
      toBoxDto: jest.fn((box) => box),
      imageAdmissionService: {
        assert: jest.fn().mockResolvedValue(undefined),
        spendColdPullBudget: jest.fn().mockResolvedValue(undefined),
      },
      imageResolverService: {
        resolve: jest.fn().mockResolvedValue({ ref: 'quay.io/acme/app@sha256:resolved', isOrgOwned: true }),
      },
      secretServerClient: disabledSecretServer(),
      configService: {
        getOrThrow: jest.fn((key: string) => {
          if (key === 'volume.filestoreInstances') {
            return { instances: [{ instance: 'ml-scratch', projectId: 'boxlite-dev', zone: 'asia-southeast1-b' }] }
          }
          throw new Error(`unexpected config key ${key}`)
        }),
      },
      filestoreInstanceResolver: {
        resolve: jest.fn().mockResolvedValue({ server: '10.0.0.7', export: '/vol1' }),
      },
      ...overrides,
    })
    return { service, boxRepository }
  }

  it('stamps the resolved id and the filestore instance into the persisted volume entry', async () => {
    const { service, boxRepository } = makeService({
      volumeService: {
        validateVolumes: jest
          .fn()
          .mockResolvedValue(new Map([['my-data', { id: 'vol-uuid-1', instance: 'ml-scratch' }]])),
      },
    })

    await service.create(
      {
        name: 'nfs-box',
        image: 'quay.io/acme/app:v1',
        volumes: [{ volumeId: 'my-data', mountPath: '/data' }],
      } as any,
      { id: 'org-1' } as any,
      Context.user(),
    )

    expect(boxRepository.insert.mock.calls[0][0]).toEqual(
      expect.objectContaining({
        volumes: [
          {
            volumeId: 'vol-uuid-1',
            mountPath: '/data',
            filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' },
          },
        ],
      }),
    )
  })

  it('fails the dispatch loudly when the instance left the configuration after the volume was created', async () => {
    const { service, boxRepository } = makeService({
      volumeService: {
        validateVolumes: jest
          .fn()
          .mockResolvedValue(new Map([['my-data', { id: 'vol-uuid-1', instance: 'ml-scratch' }]])),
      },
      filestoreInstanceResolver: {
        resolve: jest.fn().mockRejectedValue(new BadRequestError("unknown Filestore instance 'ml-scratch'")),
      },
    })

    await expect(
      service.create(
        {
          name: 'nfs-box',
          image: 'quay.io/acme/app:v1',
          volumes: [{ volumeId: 'my-data', mountPath: '/data' }],
        } as any,
        { id: 'org-1' } as any,
        Context.user(),
      ),
    ).rejects.toThrow("unknown Filestore instance 'ml-scratch'")
    // A failed dispatch must not leave a persisted box row behind.
    expect(boxRepository.insert).not.toHaveBeenCalled()
  })

  it('keeps a bucket-backed volume entry free of any filestore key', async () => {
    const { service, boxRepository } = makeService({
      volumeService: {
        validateVolumes: jest.fn().mockResolvedValue(new Map([['my-data', { id: 'vol-uuid-2', instance: undefined }]])),
      },
    })

    await service.create(
      {
        name: 'bucket-box',
        image: 'quay.io/acme/app:v1',
        volumes: [{ volumeId: 'my-data', mountPath: '/data' }],
      } as any,
      { id: 'org-1' } as any,
      Context.user(),
    )

    expect(boxRepository.insert.mock.calls[0][0]).toEqual(
      expect.objectContaining({
        volumes: [{ volumeId: 'vol-uuid-2', mountPath: '/data' }],
      }),
    )
  })
})