Skip to content

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

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

import {
  ConflictException,
  Inject,
  Injectable,
  Logger,
  NotFoundException,
  NotImplementedException,
} from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { randomUUID } from 'node:crypto'
import { EntityManager, Repository } from 'typeorm'
import { Box } from '../../box/entities/box.entity'
import { Checkpoint } from '../../box/entities/checkpoint.entity'
import { BoxDesiredState } from '../../box/enums/box-desired-state.enum'
import { parseImageRef, upstreamRefOf } from '../../image/utils/image-ref.util'
import { CreateRegistryCredentialDto, UpdateRegistryCredentialDto } from '../dto/registry-credential.dto'
import { RegistryCredential } from '../entities/registry-credential.entity'
import { RegistryCredentialKind } from '../enums/registry-credential-kind.enum'
import { SecretStore } from '../stores/secret.store'
import { matchingCredential } from '../utils/matching-credential'
import { registryProxyHost } from '../utils/registry-proxy.util'

/** The injection token the module binds `createSecretStore`'s answer to. */
export const SECRET_STORE = Symbol('SECRET_STORE')

const PG_UNIQUE_VIOLATION = '23505'

/**
 * An organization's registry logins, as its members manage them.
 *
 * The password is in this process for one create or update: from the
 * request body to the secret store, never onto an entity, a log line or an
 * answer. What comes back, and what can be listed, is the row, which has no
 * password to leave out.
 */
@Injectable()
export class RegistriesService {
  private readonly logger = new Logger(RegistriesService.name)

  constructor(
    @InjectRepository(RegistryCredential)
    private readonly credentials: Repository<RegistryCredential>,
    @Inject(SECRET_STORE)
    private readonly store: SecretStore | null,
  ) {}

  list(organizationId: string): Promise<RegistryCredential[]> {
    return this.credentials.find({ where: { organizationId }, order: { createdAt: 'ASC' } })
  }

  async create(
    organizationId: string,
    createdBy: string | null,
    request: CreateRegistryCredentialDto,
  ): Promise<RegistryCredential> {
    const store = this.enabledStore()
    const id = randomUUID()
    const repositoryPrefix = request.repositoryPrefix ?? ''

    // The secret first, so no row ever names a version that was never written.
    const secretVersion = await store.put(id, request.password)
    try {
      await this.credentials.insert({
        id,
        organizationId,
        kind: RegistryCredentialKind.BASIC,
        registryHost: request.registryHost,
        repositoryPrefix,
        username: request.username,
        secretVersion,
        createdBy,
      })
    } catch (error) {
      // A password no row points at would stay readable by the proxy, so it
      // is destroyed on the way out. The empty secret it leaves is harmless:
      // the API holds no permission to delete one.
      await this.destroyQuietly(secretVersion)
      if ((error as { code?: string }).code === PG_UNIQUE_VIOLATION) {
        // The code names the conflict for an SDK, which would otherwise read a
        // bare 409 as a resource in the wrong state, as a delete's refusal is.
        throw new ConflictException({
          message: `A credential for ${request.registryHost}/${repositoryPrefix} already exists; update it to replace the login`,
          code: 'already_exists',
        })
      }
      throw error
    }
    return this.credentials.findOneByOrFail({ id })
  }

  async update(organizationId: string, id: string, request: UpdateRegistryCredentialDto): Promise<RegistryCredential> {
    const store = this.enabledStore()
    if (!(await this.credentials.findOneBy({ id, organizationId }))) {
      throw new NotFoundException(`Registry credential ${id} not found`)
    }
    // Secret I/O must not hold a database connection or the credential's row lock.
    const replacementVersion = await store.put(randomUUID(), request.password)
    let previousVersion: string | undefined
    let callbackCompleted = false
    let result: { credential: RegistryCredential; previousVersion: string }
    try {
      result = await this.credentials.manager.transaction('READ COMMITTED', async (manager) => {
        const credential = await manager.findOne(RegistryCredential, {
          where: { id, organizationId },
          lock: { mode: 'pessimistic_write', onLocked: 'nowait' },
        })
        if (!credential) throw new NotFoundException(`Registry credential ${id} not found`)
        // Another rotation may have committed while the replacement was being written.
        previousVersion = credential.secretVersion
        await manager.update(
          RegistryCredential,
          { id, organizationId },
          { username: request.username, secretVersion: replacementVersion },
        )
        callbackCompleted = true
        return {
          credential: { ...credential, username: request.username, secretVersion: replacementVersion },
          previousVersion: credential.secretVersion,
        }
      })
    } catch (error) {
      if (callbackCompleted) {
        // A rejected COMMIT can have succeeded remotely. Preserve both versions
        // until the stored pointer can be reconciled; never destroy a live login.
        this.logger.warn(
          `Registry credential ${id} update outcome is unknown; reconcile secrets ${previousVersion} and ${replacementVersion} before cleanup`,
        )
      } else {
        // TypeORM has not reached COMMIT; clean up after the transaction releases its resources.
        await this.destroyQuietly(replacementVersion)
      }
      if ((error as { code?: string }).code === '55P03') {
        throw new ConflictException(`Registry credential ${id} is in use by another request; retry update`)
      }
      throw error
    }
    await this.destroyQuietly(result.previousVersion)
    return result.credential
  }

  /**
   * Remove a login, unless a box still pulls through it.
   *
   * A box counts when its image goes through the proxy, on this host, and this
   * login is the one the longest-prefix match picks for it now. A shorter login
   * shadowed by a longer one can go without breaking anything.
   *
   * The version is destroyed before the row is removed: the other order, on a
   * failure between the two, would leave a password the proxy can still read
   * with nothing listing it.
   */
  async delete(organizationId: string, id: string): Promise<void> {
    try {
      await this.credentials.manager.transaction('READ COMMITTED', async (manager) => {
        // Box insertion holds a shared lock through commit. Do not wait on
        // that work, or let a new insert race the secret-store operation.
        const credential = await manager.findOne(RegistryCredential, {
          where: { id, organizationId },
          lock: { mode: 'pessimistic_write', onLocked: 'nowait' },
        })
        if (!credential) {
          throw new NotFoundException(`Registry credential ${id} not found`)
        }
        const inUse = await this.boxesPullingThrough(credential, manager)
        if (inUse.length > 0) {
          throw new ConflictException(
            `Registry credential ${id} cannot be removed while ${inUse.length} box(es) pull through it: ${inUse.join(', ')}`,
          )
        }
        await this.assertNoCheckpointUsing(credential, manager)
        await this.enabledStore().destroy(credential.secretVersion)
        await manager.delete(RegistryCredential, { id, organizationId })
      })
    } catch (error) {
      if ((error as { code?: string }).code === '55P03') {
        throw new ConflictException(`Registry credential ${id} is in use by another request; retry removal`)
      }
      throw error
    }
  }

  private async boxesPullingThrough(credential: RegistryCredential, manager: EntityManager): Promise<string[]> {
    const proxyHost = registryProxyHost()
    if (!proxyHost) {
      return []
    }
    const candidates = await manager
      .getRepository(Box)
      .createQueryBuilder('box')
      .where('box.organizationId = :organizationId', { organizationId: credential.organizationId })
      .andWhere('box.desiredState != :destroyed', { destroyed: BoxDesiredState.DESTROYED })
      .andWhere('box.image LIKE :through', {
        // The prefix a proxy ref for this organization and host starts with.
        // `_` would be a LIKE wildcard, and neither a host nor a uuid holds one.
        through: `${proxyHost}/${credential.organizationId}/${credential.registryHost}/%`,
      })
      .select(['box.id', 'box.image'])
      .getMany()

    if (candidates.length === 0) return []
    const credentials = await manager.getRepository(RegistryCredential).find({
      where: { organizationId: credential.organizationId, registryHost: credential.registryHost },
    })
    const inUse: string[] = []
    for (const box of candidates) {
      const { repository } = parseImageRef(upstreamRefOf(box.image as string))
      const picked = matchingCredential(credentials, repository)
      if (picked?.id === credential.id) {
        inUse.push(box.id)
      }
    }
    return inUse
  }

  private async assertNoCheckpointUsing(credential: RegistryCredential, manager: EntityManager): Promise<void> {
    const proxy = registryProxyHost()
    if (!proxy) return
    const prefix = `${proxy}/${credential.organizationId}/${credential.registryHost}/`
    const checkpoints = await manager.getRepository(Checkpoint).find({
      where: { organizationId: credential.organizationId },
      select: ['id', 'environment', 'archive'],
    })
    const candidates = checkpoints
      .map((checkpoint) => ({
        checkpoint,
        refs: [checkpoint.environment.image, checkpoint.archive?.pinnedImage].filter(
          (ref): ref is string => !!ref?.startsWith(prefix),
        ),
      }))
      .filter((item) => item.refs.length)
    if (!candidates.length) return
    const credentials = await manager.getRepository(RegistryCredential).find({
      where: { organizationId: credential.organizationId, registryHost: credential.registryHost },
    })
    const retained = candidates.filter(({ refs }) =>
      refs.some(
        (ref) => matchingCredential(credentials, parseImageRef(upstreamRefOf(ref)).repository)?.id === credential.id,
      ),
    )
    if (retained.length)
      throw new ConflictException(
        `Registry credential ${credential.id} cannot be removed while checkpoint(s) use it: ${retained.map((item) => item.checkpoint.id).join(', ')}`,
      )
  }

  /**
   * The store, or a 501 when this deployment keeps none: without it there is
   * nowhere to put a password, and without the proxy nothing would present
   * one. The code lets an SDK read it as unsupported rather than a fault.
   */
  private enabledStore(): SecretStore {
    if (!this.store || !registryProxyHost()) {
      throw new NotImplementedException({
        message: 'Private registries are not enabled in this deployment',
        code: 'unsupported',
      })
    }
    return this.store
  }

  private async destroyQuietly(secretVersion: string): Promise<void> {
    try {
      await this.enabledStore().destroy(secretVersion)
    } catch (error) {
      this.logger.warn(
        `Could not destroy unused registry secret ${secretVersion}; retry cleanup: ${(error as Error)?.message ?? String(error)}`,
      )
    }
  }
}