Skip to content

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

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

import {
  BadRequestException,
  ConflictException,
  Injectable,
  Logger,
  NotFoundException,
  ServiceUnavailableException,
} from '@nestjs/common'
import { GoogleAuth } from 'google-auth-library'
import { TypedConfigService } from '../../config/typed-config.service'
import { BoxSecret } from '../dto/box.dto'
import { BadRequestError } from '../../exceptions/bad-request.exception'

const TRANSFER_TIMEOUT_MS = 6000
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i

export type NamedSecret = { secret: string }
export type OrganizationSecretIdentity = { id: string; name: string }
type OrganizationSecretListItem = OrganizationSecretIdentity & {
  hosts: string[]
  headers: Record<string, string>
  placeholder: string
}

function normalizedName(name: string): string {
  return name.replace(/[a-z]/g, (letter) => letter.toUpperCase()).replace(/[^A-Z0-9_]/gu, '_')
}

class SecretResponseError extends Error {
  constructor(readonly status: number) {
    super()
  }
}

@Injectable()
export class SecretServerClient {
  private readonly logger = new Logger(SecretServerClient.name)
  private readonly auth = new GoogleAuth()

  constructor(private readonly config: TypedConfigService) {}

  get enabled(): boolean {
    return this.config.get('secretServer.enabled')
  }

  async retireBoxSecrets(orgId: string, boxId: string): Promise<void> {
    await this.withDeadline(async (signal) => {
      const path = `/internal/v1/boxes/${encodeURIComponent(boxId)}/secrets`
      const response = await this.request(path, undefined, signal, 'DELETE', { 'X-Boxlite-Organization-Id': orgId })
      await response.body?.cancel()
      if (response.status !== 204) throw new Error('Secret retirement failed')
    })
  }

  validateInline(secrets: BoxSecret[]): void {
    if (secrets.length > 64) throw new BadRequestError('secrets must contain at most 64 entries')
    // Match the write contract's ASCII name normalization before any remote side effect.
    const names = new Set<string>()
    for (const [index, { name, value, placeholder }] of secrets.entries()) {
      const normalized = normalizedName(name)
      if (normalized.length < 1 || normalized.length > 64) {
        throw new BadRequestError(`secrets[${index}].name must normalize to 1–64 characters`)
      }
      if (
        typeof value !== 'string' ||
        Buffer.byteLength(value, 'utf8') < 1 ||
        Buffer.byteLength(value, 'utf8') > 65536
      ) {
        throw new BadRequestError(`secrets[${index}].value must contain 1–65536 UTF-8 bytes`)
      }
      if (placeholder === '') throw new BadRequestError(`secrets[${index}].placeholder must not be empty`)
      if (names.has(normalized)) throw new BadRequestError('Secret names must be unique after normalization')
      names.add(normalized)
    }
  }

  async storeBoxSecrets(
    boxId: string,
    orgId: string,
    createdBy: string | undefined,
    secrets: BoxSecret[],
  ): Promise<BoxSecret[]> {
    if (!this.config.get('secretServer.enabled') || secrets.length === 0) return secrets

    this.validateInline(secrets)

    const started = Date.now()
    let result = 'failure'
    try {
      const references = await this.withDeadline((signal) => this.transfer(boxId, orgId, createdBy, secrets, signal))
      result = 'success'
      return references
    } finally {
      this.logger.log({ boxId, count: secrets.length, result, latencyMs: Date.now() - started })
    }
  }

  private async withDeadline<T>(operation: (signal: AbortSignal) => Promise<T>): Promise<T> {
    const controller = new AbortController()
    let timer: ReturnType<typeof setTimeout>
    const deadline = new Promise<never>((_, reject) => {
      timer = setTimeout(() => {
        controller.abort()
        reject(new Error('Secret transfer deadline exceeded'))
      }, TRANSFER_TIMEOUT_MS)
    })
    try {
      return await Promise.race([operation(controller.signal), deadline])
    } catch (error) {
      if (error instanceof SecretResponseError) {
        if (error.status === 409) throw new ConflictException('Secret name is already in use')
        if (error.status === 404) throw new NotFoundException('Secret not found')
        if (error.status === 422) throw new BadRequestException('Invalid organization secret')
      }
      throw new ServiceUnavailableException({ code: 'secret_store_unavailable', message: 'Secret store unavailable' })
    } finally {
      clearTimeout(timer)
    }
  }

  private async organizationRequest(
    orgId: string,
    suffix: string,
    method: 'POST' | 'GET' | 'HEAD' | 'DELETE',
    status: number,
    payload?: unknown,
  ): Promise<unknown> {
    if (!this.config.get('secretServer.enabled')) throw new ServiceUnavailableException('Secret store unavailable')
    return this.withDeadline(async (signal) => {
      const path = `/internal/v1/organizations/${encodeURIComponent(orgId)}/secrets${suffix}`
      const response = await this.request(path, payload, signal, method)
      if (response.status !== status) {
        await response.body?.cancel()
        throw new SecretResponseError(response.status)
      }
      if (status !== 204) return response.json()
    })
  }

  async createOrganizationSecret(
    orgId: string,
    creator: string,
    secret: BoxSecret,
  ): Promise<OrganizationSecretIdentity> {
    const body = await this.organizationRequest(orgId, '', 'POST', 201, {
      created_by: creator,
      secret: {
        name: secret.name,
        value: secret.value,
        hosts: secret.hosts,
        headers: secret.headers,
        placeholder: secret.placeholder ?? `<BOXLITE_SECRET:${secret.name}>`,
      },
    })
    if (
      !body ||
      typeof body !== 'object' ||
      !('id' in body) ||
      typeof body.id !== 'string' ||
      !UUID.test(body.id) ||
      !('name' in body) ||
      body.name !== secret.name
    )
      throw new ServiceUnavailableException('Invalid secret store response')
    return { id: body.id, name: secret.name }
  }

  async listOrganizationSecrets(
    org: string,
    after: string | undefined,
    limit: number,
  ): Promise<OrganizationSecretListItem[]> {
    const query = new URLSearchParams({ limit: String(limit) })
    if (after) query.set('after', after)
    const body = await this.organizationRequest(org, '?' + query.toString(), 'GET', 200)
    if (
      !body ||
      typeof body !== 'object' ||
      !('secrets' in body) ||
      !Array.isArray(body.secrets) ||
      body.secrets.length > limit
    )
      throw new ServiceUnavailableException('Invalid secret store response')
    return body.secrets.map((item) => {
      if (
        !item ||
        typeof item.id !== 'string' ||
        !UUID.test(item.id) ||
        typeof item.name !== 'string' ||
        !item.name ||
        !Array.isArray(item.hosts) ||
        !item.hosts.every((host: unknown) => typeof host === 'string') ||
        !item.headers ||
        typeof item.headers !== 'object' ||
        Array.isArray(item.headers) ||
        !Object.values(item.headers).every((template) => typeof template === 'string') ||
        typeof item.placeholder !== 'string'
      )
        throw new ServiceUnavailableException('Invalid secret store response')
      const { id, name, hosts, headers, placeholder } = item
      return { id, name, hosts, headers, placeholder }
    })
  }

  async checkOrganizationSecret(org: string, id: string): Promise<void> {
    await this.organizationRequest(org, '/' + encodeURIComponent(id), 'HEAD', 204)
  }

  async deleteOrganizationSecret(org: string, id: string): Promise<void> {
    await this.organizationRequest(org, '/' + encodeURIComponent(id), 'DELETE', 204)
  }

  async resolveForBox(orgId: string, entries: (BoxSecret | NamedSecret)[]): Promise<BoxSecret[]> {
    if (entries.some((entry) => 'secretId' in entry)) throw new BadRequestError('Secret IDs are server-assigned')
    const names = entries.filter((entry): entry is NamedSecret => 'secret' in entry)
    if (!names.length) return entries as BoxSecret[]
    if (entries.length > 64) throw new BadRequestError('secrets must contain at most 64 entries')
    if (names.some((entry) => typeof entry.secret !== 'string' || Object.keys(entry).length !== 1))
      throw new BadRequestError('A named secret accepts only a name')
    const keys = entries.map((entry) => normalizedName('secret' in entry ? entry.secret : entry.name))
    if (keys.some((key) => !key || key.length > 64) || new Set(keys).size !== keys.length)
      throw new BadRequestError('Invalid or duplicate secret names')
    const body = await this.organizationRequest(orgId, '/resolve', 'POST', 200, {
      names: names.map((entry) => entry.secret),
    })
    if (
      !body ||
      typeof body !== 'object' ||
      !('secrets' in body) ||
      !Array.isArray(body.secrets) ||
      body.secrets.length !== names.length
    )
      throw new ServiceUnavailableException('Invalid secret store response')
    const resolved = new Map<string, BoxSecret>()
    const ids = new Set<string>()
    for (const [i, item] of body.secrets.entries()) {
      if (
        !item ||
        typeof item.name !== 'string' ||
        normalizedName(item.name) !== normalizedName(names[i].secret) ||
        typeof item.id !== 'string' ||
        !UUID.test(item.id) ||
        ids.has(item.id.toLowerCase()) ||
        !Array.isArray(item.hosts) ||
        !item.hosts.every((host: unknown) => typeof host === 'string' && host) ||
        typeof item.placeholder !== 'string' ||
        !item.placeholder ||
        !item.headers ||
        typeof item.headers !== 'object'
      )
        throw new ServiceUnavailableException('Invalid secret store response')
      ids.add(item.id.toLowerCase())
      resolved.set(names[i].secret, {
        name: item.name,
        secretId: item.id,
        hosts: item.hosts,
        headers: item.headers,
        placeholder: item.placeholder,
      })
    }
    return entries.map((entry) => ('secret' in entry ? resolved.get(entry.secret)! : entry))
  }

  private async request(
    path: string,
    payload: unknown,
    signal: AbortSignal,
    method = 'POST',
    headers: Record<string, string> = {},
  ): Promise<Response> {
    const url = this.config.get('secretServer.url')
    const devToken = this.config.get('secretServer.devToken')
    const authorization = devToken
      ? `Bearer ${devToken}`
      : (await (await this.auth.getIdTokenClient(url)).getRequestHeaders()).get('authorization')
    // Identity acquisition cannot be cancelled by the library. Never start a late POST.
    signal.throwIfAborted()
    if (!authorization) throw new Error('Caller identity unavailable')
    return fetch(url + path, {
      method,
      headers: { authorization, 'content-type': 'application/json', ...headers },
      body: JSON.stringify(payload),
      redirect: 'error',
      signal,
    })
  }

  private async transfer(
    boxId: string,
    orgId: string,
    createdBy: string | undefined,
    secrets: BoxSecret[],
    signal: AbortSignal,
  ): Promise<BoxSecret[]> {
    if (!createdBy) throw new Error('Creator identity required')
    const payload = secrets.map(({ name, value, hosts, headers, placeholder }) => ({
      name,
      value,
      hosts,
      headers,
      placeholder: placeholder ?? `<BOXLITE_SECRET:${name}>`,
    }))
    const response = await this.request(
      `/internal/v1/boxes/${encodeURIComponent(boxId)}/secrets`,
      {
        org_id: orgId,
        created_by: createdBy,
        secrets: payload,
      },
      signal,
    )
    if (response.status !== 200 && response.status !== 201) {
      await response.body?.cancel()
      throw new Error('Secret transfer rejected')
    }
    const body: unknown = await response.json()
    if (
      !body ||
      typeof body !== 'object' ||
      !('secrets' in body) ||
      !Array.isArray(body.secrets) ||
      body.secrets.length !== secrets.length
    ) {
      throw new Error('Invalid secret mapping')
    }
    const expectedNames = new Set(secrets.map(({ name }) => name))
    const idsByName = new Map<string, string>()
    const ids = new Set<string>()
    for (const entry of body.secrets) {
      if (
        !entry ||
        typeof entry !== 'object' ||
        !expectedNames.has(entry.name) ||
        idsByName.has(entry.name) ||
        typeof entry.secret_id !== 'string' ||
        !UUID.test(entry.secret_id) ||
        ids.has(entry.secret_id.toLowerCase())
      ) {
        throw new Error('Invalid secret mapping')
      }
      idsByName.set(entry.name, entry.secret_id)
      ids.add(entry.secret_id.toLowerCase())
    }
    return payload.map(({ name, hosts, headers, placeholder }) => ({
      name,
      hosts,
      headers,
      placeholder,
      secretId: idsByName.get(name),
    }))
  }
}