Skip to content

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

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

import { Injectable, InternalServerErrorException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { assertSupportedImage } from '../../box/constants/curated-images.constant'
import { Organization } from '../../organization/entities/organization.entity'
import { RegistryCredentialService } from '../../registry/services/registry-credential.service'
import { registryProxyHost } from '../../registry/utils/registry-proxy.util'
import { ImageVersion } from '../entities/image-version.entity'
import { ImageVersionState } from '../enums/image-version-state.enum'
import {
  assertHostIsAllowed,
  IMPLICIT_TAG,
  imageRegistryAllowlist,
  isCuratedSelector,
  isDigestPinned,
  parseImageRef,
  proxyRefOf,
} from '../utils/image-ref.util'

/** What a box should boot from, and where that answer came from. */
export type ResolvedImage = {
  /** The ref handed to the runner. */
  ref: string
  /**
   * False only for the curated set, which every organization shares. A ref a
   * tenant named is org-owned whether or not the catalog knew it — a miss means
   * it has not been pulled yet, not that it belongs to everyone.
   */
  isOrgOwned: boolean
  /** The catalog row this resolved through, absent when nothing matched. */
  imageId?: string
}

/**
 * Turns what a caller asked for into the ref a runner is given.
 *
 * Four cases, and the first one is the whole point of the ordering: a curated
 * selector is answered from the curated set without touching the database, so
 * the path every existing caller takes stays exactly as expensive as it was —
 * and no registered login can take a curated image off it, not even one for
 * its whole host. The other three look the organization's catalog up, and a
 * miss is not an error — it means this image has not been pulled yet, and the
 * unpinned ref is passed through so the runner can pull it and report what it
 * got.
 *
 * Whichever of those answers, a repository the organization registered a
 * login for is then handed to the runner as a registry proxy ref, which is
 * the only way that login is ever presented.
 *
 * A hit must come back digest-pinned. That is the assertion at the bottom, and
 * it is load-bearing rather than defensive: the catalog promises that a ref
 * boots the version its tag points at in the catalog, and a runner handed a
 * tag asks the registry again whenever it builds a new disk from it. A hit that
 * came back unpinned would let every new box follow `app:stable` upstream
 * instead.
 */
@Injectable()
export class ImageResolverService {
  constructor(
    @InjectRepository(ImageVersion)
    private readonly versionRepository: Repository<ImageVersion>,
    private readonly registryCredentials: RegistryCredentialService,
  ) {}

  async resolve(organization: Organization, image: string | undefined): Promise<ResolvedImage> {
    if (isCuratedSelector(image)) {
      return { ref: assertSupportedImage(image), isOrgOwned: false }
    }

    const ref = image as string
    const { host, repository, tag, digest } = parseImageRef(ref)
    const name = `${host}/${repository}`

    const resolved = digest
      ? await this.resolveByDigest(organization, name, ref, digest)
      : await this.resolveByTag(organization, name, ref, tag ?? IMPLICIT_TAG)

    assertPinnedOnCatalogHit(resolved)
    if (!(await this.registryCredentials.routesThroughProxy(organization.id, host, repository))) {
      // Admission asked the same question a moment ago, and a login removed
      // since would make that answer stale: its host admitted for the proxy,
      // then handed to the runner direct. So a direct ref is held to the
      // allowlist here too, where the decision is final.
      assertHostIsAllowed(host, imageRegistryAllowlist())
      return resolved
    }
    // routesThroughProxy is false without a proxy host, so it is set here.
    return { ...resolved, ref: proxyRefOf(registryProxyHost() as string, organization.id, parseImageRef(resolved.ref)) }
  }

  /**
   * A ref the caller already pinned. The lookup adds no pinning — it only says
   * whether the catalog knows this digest, which is what tells a later step
   * there is a row to touch.
   */
  private async resolveByDigest(
    organization: Organization,
    name: string,
    ref: string,
    digest: string,
  ): Promise<ResolvedImage> {
    const version = await this.versionRepository
      .createQueryBuilder('version')
      .innerJoin('image', 'image', 'image.id = version."imageId"')
      .where('image."organizationId" = :organizationId', { organizationId: organization.id })
      .andWhere('image.name = :name', { name })
      // A soft-deleted image must not resolve, or deleting one would stop being
      // the way to pick up a tag that moved upstream.
      .andWhere('image."deletedAt" IS NULL')
      .andWhere('version.digest = :digest', { digest })
      .andWhere('version.state = :state', { state: ImageVersionState.READY })
      .select('version."imageId"', 'imageId')
      .getRawOne<{ imageId: string }>()

    return version ? { ref, isOrgOwned: true, imageId: version.imageId } : { ref, isOrgOwned: true }
  }

  /**
   * A tag, resolved to the version it points at in the catalog: the one the
   * pull that recorded it found, until the organization moves it. It is
   * deliberately not re-checked against the registry: the tag may have moved
   * upstream, and following it would change what a box boots from without
   * anyone asking.
   */
  private async resolveByTag(
    organization: Organization,
    name: string,
    ref: string,
    tag: string,
  ): Promise<ResolvedImage> {
    const hit = await this.versionRepository
      .createQueryBuilder('version')
      .innerJoin('image', 'image', 'image.id = version."imageId"')
      .innerJoin('image_tag', 'tag', 'tag."versionId" = version.id')
      .where('image."organizationId" = :organizationId', { organizationId: organization.id })
      .andWhere('image.name = :name', { name })
      .andWhere('image."deletedAt" IS NULL')
      .andWhere('tag.name = :tag', { tag })
      .andWhere('version.state = :state', { state: ImageVersionState.READY })
      .select('version.digest', 'digest')
      .addSelect('version."imageId"', 'imageId')
      .getRawOne<{ digest: string; imageId: string }>()

    if (!hit) {
      // The caller's own string, not a normalised one: a miss has nothing to
      // add, and rewriting `acme/app` into `docker.io/acme/app:latest` would
      // put this resolver's spelling in front of a runner that already has its
      // own. The two paths agree on that — neither touches a ref it did not
      // resolve.
      return { ref, isOrgOwned: true }
    }
    return { ref: `${name}@${hit.digest}`, isOrgOwned: true, imageId: hit.imageId }
  }
}

/**
 * A catalog hit has to be digest-pinned. A runner re-resolves a tag it is
 * handed whenever it builds a new disk, so an unpinned hit would let each box
 * follow the tag upstream rather than boot the build the catalog recorded — a
 * failure that is silent everywhere else, which is why it is caught here.
 *
 * Not a `BadRequestError`: the caller did nothing wrong, the resolver did.
 */
export function assertPinnedOnCatalogHit(resolved: ResolvedImage): void {
  if (resolved.imageId && !isDigestPinned(resolved.ref)) {
    throw new InternalServerErrorException(`Resolved '${resolved.ref}' from the image catalog without pinning a digest`)
  }
}