Skip to content

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

15.0 KB
Raw Blame
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
import { StackEnvError, readStackEnvironment } from '../src/stack-env.ts'
import type { GroupDeclaration } from '../src/env.ts'
import { assertAddressesAreNotSpent } from '../src/env.ts'
import { parseBase } from 'mstage/config'

const SHA = 'a'.repeat(40)
const DIGEST = 'b'.repeat(64)

const declaration: GroupDeclaration = {
  groups: { deploy: [], api: ['OIDC_CLIENT_ID'], proxy: ['PROXY_API_KEY'], 'otel-collector': [], runner: [] },
  where: '/repo/mstage.config.json',
}

const complete = {
  BOXLITE_IMAGE_TAG: SHA,
  STACK_DOMAIN: 'dev.boxlite.ai',
  PROXY_DOMAIN: 'box.dev.boxlite.ai',
  CLOUDFLARE_ZONE_ID: 'zone-1',
  OIDC_ISSUER_BASE_URL: 'https://auth.dev.boxlite.ai',
  OIDC_CLIENT_ID: 'client-1',
  PROXY_API_KEY: 'proxy-key',
}

const read = (environment: Record<string, string | undefined>) =>
  readStackEnvironment({
    environment,
    declaration,
    app: 'boxlite-app',
    stage: 'dev',
    region: 'ap-southeast-1',
    home: 'aws',
  })

for (const home of ['aws', 'gcp'] as const) {
  const deployment = (metadata: NodeJS.ProcessEnv) =>
    readStackEnvironment({
      environment: { ...complete, ...metadata },
      declaration,
      app: 'boxlite-app',
      stage: 'dev',
      region: 'ap-southeast-1',
      home,
    })
  test(`${home} omits scheduler generation when invocation metadata is absent`, () => {
    assert.equal(Object.hasOwn(deployment({}).apiEnvironment, 'CI_SCHEDULER_GENERATION'), false)
  })
  test(`${home} delivers the workflow run ID as the exact API scheduler generation`, () => {
    const { apiEnvironment, proxyEnvironment, runnerEnvironment } = deployment({ GITHUB_RUN_ID: '9007199254740991' })
    assert.equal(apiEnvironment.CI_SCHEDULER_GENERATION, '9007199254740991')
    assert.equal(Object.hasOwn(apiEnvironment, 'GITHUB_RUN_ID'), false)
    assert.equal(Object.hasOwn(proxyEnvironment, 'CI_SCHEDULER_GENERATION'), false)
    assert.equal(Object.hasOwn(runnerEnvironment, 'CI_SCHEDULER_GENERATION'), false)
  })
  test(`${home} prefers an explicit scheduler generation over workflow metadata`, () => {
    assert.equal(
      deployment({ CI_SCHEDULER_GENERATION: '27', GITHUB_RUN_ID: '26' }).apiEnvironment.CI_SCHEDULER_GENERATION,
      '27',
    )
    assert.equal(deployment({ CI_SCHEDULER_GENERATION: '1' }).apiEnvironment.CI_SCHEDULER_GENERATION, '1')
  })
  for (const key of ['CI_SCHEDULER_GENERATION', 'GITHUB_RUN_ID']) {
    for (const value of ['', '0', '-1', '01', ' 1', '1 ', '1.5', '1e3', '9007199254740992', 'NaN']) {
      test(`${home} rejects invalid ${key} invocation metadata ${JSON.stringify(value)}`, () => {
        assert.throws(
          () => deployment({ GITHUB_RUN_ID: '25', [key]: value }),
          (error: unknown) => error instanceof StackEnvError && error.message.includes(key),
        )
      })
    }
  }
}

test('a complete environment resolves everything one deploy decides', () => {
  const resolved = read(complete)
  assert.equal(resolved.tag, SHA)
  assert.equal(resolved.domain, 'dev.boxlite.ai')
  assert.equal(resolved.proxyProtocol, 'http', 'a default, because the hop is inside the network')
  assert.equal(resolved.senderDomain, null, 'a stage that names none sends no mail')
  assert.deepEqual(resolved.runnerFleet, [
    // `<app>-<stage>-runner`, the same shape every other resource carries: a
    // name without the stage cannot be deployed twice into one project.
    { resourceName: 'Runner', nameTag: 'boxlite-app-dev-runner', controlPlaneRunnerName: 'default' },
  ])
  assert.deepEqual(resolved.proxySecrets, {})
  assert.deepEqual(resolved.proxyEnvironment, { PROXY_API_KEY: 'proxy-key' })
})

test('the dashboard stays on the stage domain unless the stage names another host', () => {
  // Absent is the common stage, which serves both halves under one domain.
  // Named only by a stage whose domain belongs to something else — prod, whose
  // apex is the marketing site's. The control plane is not part of the pair:
  // it stays `api.<STACK_DOMAIN>`, which is what each runner is handed.
  assert.equal(read(complete).dashboardDomain, null)
  assert.equal(read({ ...complete, DASHBOARD_DOMAIN: 'app.dev.boxlite.ai' }).dashboardDomain, 'app.dev.boxlite.ai')
})

test('a stage names a user domain of its own, in its own zone, or offers named apps nowhere', () => {
  // Unset is a stage with no named apps: no fallback under the stage domain.
  assert.equal(read(complete).userDomain, null)
  assert.deepEqual(
    read({ ...complete, STACK_USER_DOMAIN: ' Apps.Example ', CLOUDFLARE_USER_ZONE_ID: 'user-zone' }).userDomain,
    { domain: 'apps.example', dnsZoneId: 'user-zone' },
  )
  // A different registrable domain sits in a different zone, so the stage names it.
  assert.throws(() => read({ ...complete, STACK_USER_DOMAIN: 'apps.example' }), /CLOUDFLARE_USER_ZONE_ID is required/)
})

test("a user domain under the stage's registrable domain is refused", () => {
  // Anywhere under boxlite.ai a user's page is same-site with the dashboard and
  // a blocklist entry lands on the platform's domain; that separation is the
  // setting's whole point, so a sibling of the stage domain is refused too.
  for (const domain of ['dev.boxlite.ai', 'app.dev.boxlite.ai', 'boxlite.ai', 'apps.boxlite.ai', 'DEV.boxlite.ai']) {
    assert.throws(
      () => read({ ...complete, STACK_USER_DOMAIN: domain, CLOUDFLARE_USER_ZONE_ID: 'user-zone' }),
      /shares boxlite\.ai with STACK_DOMAIN dev\.boxlite\.ai/,
      domain,
    )
  }
  // Another registrable domain is accepted, including one that merely ends in the same letters.
  for (const domain of ['boxlite.page', 'dev.boxlite.site', 'xboxlite.ai']) {
    assert.equal(
      read({ ...complete, STACK_USER_DOMAIN: domain, CLOUDFLARE_USER_ZONE_ID: 'user-zone' }).userDomain?.domain,
      domain,
    )
  }
})

test('a user domain cannot share the overridden dashboard registrable domain', () => {
  for (const domain of ['users.dashboard.example', 'DASHBOARD.EXAMPLE']) {
    assert.throws(
      () =>
        read({
          ...complete,
          DASHBOARD_DOMAIN: 'console.dashboard.example',
          STACK_USER_DOMAIN: domain,
          CLOUDFLARE_USER_ZONE_ID: 'user-zone',
        }),
      /shares dashboard\.example with DASHBOARD_DOMAIN/,
    )
  }
  assert.equal(
    read({
      ...complete,
      DASHBOARD_DOMAIN: 'console.dashboard.example',
      STACK_USER_DOMAIN: 'apps.independent.example',
      CLOUDFLARE_USER_ZONE_ID: 'user-zone',
    }).userDomain?.domain,
    'apps.independent.example',
  )
})

test('the OpenAPI reader uses only the fixed feature flag', () => {
  for (const flag of [undefined, '', ' ', 'false', 'true', ' true ']) {
    const result = read({ ...complete, OTEL_OPENAPI_ENABLED: flag })
    assert.equal(result.otelOpenapiEnabled, flag?.trim() === 'true')
    assert.ok(!('OTEL_OPENAPI_ENABLED' in result.apiEnvironment))
  }
  for (const flag of ['1', 'yes', 'TRUE', 'invalid']) {
    assert.throws(() => read({ ...complete, OTEL_OPENAPI_ENABLED: flag }), /OTEL_OPENAPI_ENABLED/)
  }
})

test('the manifest fingerprints the optional flag without exposing credential configuration', () => {
  const path = new URL('../../mstage.env.json', import.meta.url).pathname
  const config = { ...parseBase(path, readFileSync(path, 'utf8')), path }
  assert.ok(config.envOptional.deploy?.includes('OTEL_OPENAPI_ENABLED'))
  assert.ok(config.envSelectGroup[config.envDigest!.group]!.includes('OTEL_OPENAPI_ENABLED'))
  for (const group of Object.values(config.envSelectGroup)) {
    assert.ok(!group.some((key) => key.startsWith('CLICKHOUSE_OPENAPI_LOG_READER')))
  }
  assert.doesNotThrow(() => assertAddressesAreNotSpent(config))
})

test('a key nothing supplies stops the deploy, named, before anything is built', () => {
  for (const key of ['BOXLITE_IMAGE_TAG', 'STACK_DOMAIN', 'PROXY_DOMAIN', 'CLOUDFLARE_ZONE_ID']) {
    assert.throws(
      () => read({ ...complete, [key]: undefined }),
      new RegExp(`${key} is required`),
      `${key} is not required`,
    )
  }
})

test('a tag that is not one full commit sha is refused', () => {
  // A deploy names exact bytes. A branch name or a short sha would resolve to
  // an address nothing published, and the failure would land on a task that
  // cannot pull — after the apply had already created resources.
  assert.throws(() => read({ ...complete, BOXLITE_IMAGE_TAG: 'main' }), /must be one full lowercase commit SHA/)
  assert.throws(() => read({ ...complete, BOXLITE_IMAGE_TAG: SHA.toUpperCase() }), /lowercase/)
  // The release build of that commit is a different image at a different
  // address, and it has to reach an apply. This check used to carry its own
  // copy of mbuild's tag pattern, so a release image would have published fine
  // and then been refused here; it reads mbuild's constant now.
  assert.equal(read({ ...complete, BOXLITE_IMAGE_TAG: `v1.2.3-${SHA}` }).tag, `v1.2.3-${SHA}`)
  for (const rejected of [
    `v1.2.3-${SHA.slice(1)}`,
    `1.2.3-${SHA}`,
    `v1.2.3-v1.2.3-${SHA}`,
    `${SHA}-v1.2.3`,
    `release-${SHA}`,
  ]) {
    assert.throws(() => read({ ...complete, BOXLITE_IMAGE_TAG: rejected }), StackEnvError, `${rejected} was accepted`)
  }
})

test('the runner binary is not read from the environment at all', () => {
  // It used to be: three keys nothing produced, so every deploy that included
  // the runner module stopped on the first of them. The version is the
  // checkout's, and `stack/runner-binary.ts` resolves it where the resources
  // are built — so a stage that exports these names is exporting nothing.
  const resolved = read({
    ...complete,
    BOXLITE_RUNNER_BINARY_URL: 'https://example.invalid/wrong.tar.gz',
    BOXLITE_RUNNER_BINARY_SHA256: DIGEST,
  })
  assert.ok(!('runnerBinary' in resolved), 'a second answer here is a second place to keep in step')
})

test('the fleet keeps the first host’s resource name, whatever it is called', () => {
  // The resource name is what a targeted deploy selects on and what an existing
  // stage's state already calls its first host: renaming it would replace a
  // machine rather than update one.
  const fleet = read({ ...complete, RUNNERS: '3', DEFAULT_RUNNER_NAME: 'sg-1' }).runnerFleet
  assert.deepEqual(
    fleet.map((slot) => [slot.resourceName, slot.controlPlaneRunnerName]),
    [
      ['Runner', 'sg-1'],
      ['Runner-runner-2', 'runner-2'],
      ['Runner-runner-3', 'runner-3'],
    ],
  )
})

test('a fleet size this repository will not create is refused', () => {
  assert.throws(() => read({ ...complete, RUNNERS: '0' }), /must be a whole number from 1 to 100/)
  assert.throws(() => read({ ...complete, RUNNERS: '101' }), /from 1 to 100/)
  assert.throws(() => read({ ...complete, DEFAULT_RUNNER_NAME: 'a' }), /2-255 characters/)
})

test('a managed ClickHouse arrives whole or not at all', () => {
  assert.equal(read(complete).managedClickHouse, null)
  assert.throws(() => read({ ...complete, CLICKHOUSE_URL: 'https://clickhouse.invalid' }), /must be set together/)
  const managed = read({
    ...complete,
    CLICKHOUSE_URL: 'https://clickhouse.invalid',
    CLICKHOUSE_WRITER_PASSWORD_SECRET_ARN: 'arn:writer',
    CLICKHOUSE_READER_PASSWORD_SECRET_ARN: 'arn:reader',
  }).managedClickHouse
  assert.equal(managed?.url, 'https://clickhouse.invalid')
})

test('retention is read from the stage environment, or null when it set none', () => {
  assert.equal(read(complete).clickHouseRetentionHours, null)
  assert.equal(read({ ...complete, CLICKHOUSE_RETENTION_HOURS: '168' }).clickHouseRetentionHours, 168)
  assert.throws(() => read({ ...complete, CLICKHOUSE_RETENTION_HOURS: '0' }), /positive.*integer/)
})

test('the ClickStack consumer is a service account or nobody', () => {
  // Nobody is a supported state: a stage publishes to whoever is configured,
  // and a stage with no console configures none. What is not supported is a
  // value Google would reject — caught here, where the key is named, rather
  // than as a policy error during the apply.
  assert.equal(read(complete).clickStackConsumer, null)
  assert.throws(
    () => read({ ...complete, CLICKSTACK_CONSUMER_ACCOUNT: '[email protected]' }),
    /CLICKSTACK_CONSUMER_ACCOUNT must be a service account email/,
  )
  const account = '[email protected]'
  assert.equal(read({ ...complete, CLICKSTACK_CONSUMER_ACCOUNT: account }).clickStackConsumer, account)
})

test('a service group the deploy never received stops it rather than shipping a short environment', () => {
  // A container handed a silently short environment refuses a feature hours
  // later, somewhere that does not mention the key.
  assert.throws(() => read({ ...complete, OIDC_CLIENT_ID: undefined }), /OIDC_CLIENT_ID must reach the deploy/)
})

test('StackEnvError is the single failure type callers can catch', () => {
  assert.throws(
    () => read({ ...complete, BOXLITE_IMAGE_TAG: 'main' }),
    (error) => error instanceof StackEnvError,
  )
})

/*
 * One copy of the assembly, not two.
 *
 * Both engines call `readStackEnvironment`. Two copies that drifted would
 * deploy a control plane behaving differently on one cloud — the kind of
 * difference found months later, with a matching digest and nothing reporting
 * it. Asserted by reading the two engine entry points rather than by trusting
 * that nobody will paste one into the other.
 */
test('both engines read this one function rather than each reading the environment', () => {
  const entries = ['../sst.config.ts', '../pulumi/program.ts'].map((path) =>
    readFileSync(fileURLToPath(new URL(path, import.meta.url)), 'utf8'),
  )
  for (const source of entries) {
    assert.match(source, /readStackEnvironment\(/, 'an engine that assembled its own would be the drift this prevents')
    // The runner binary is the same shape of question and the same risk: one
    // commit must resolve to one binary on both clouds, and an engine that
    // composed its own release URL would install a different one on one of them.
    assert.match(source, /resolveRunnerBinary\(/, 'both engines resolve the runner binary through one function')
  }
  // And neither reaches past it for a key the assembly already owns.
  for (const source of entries) {
    assert.doesNotMatch(source, /process\.env\.BOXLITE_IMAGE_TAG/)
    assert.doesNotMatch(source, /process\.env\.STACK_DOMAIN/)
  }
})

test('runner JSON cannot shadow direct values, secrets, or generated secret addresses', () => {
  const declared = {
    ...declaration,
    groups: { ...declaration.groups, runner: ['BOXLITE_RUNNER_ENV', 'DIRECT', 'GHCR_TOKEN'], secret: ['GHCR_TOKEN'] },
  }
  for (const key of ['DIRECT', 'GHCR_TOKEN', 'GHCR_TOKEN_ARN']) {
    assert.throws(
      () =>
        readStackEnvironment({
          environment: {
            ...complete,
            DIRECT: 'direct',
            GHCR_TOKEN: JSON.stringify({ address: 'arn:aws:secretsmanager:us-east-1:123456789012:secret:ghcr-abcdef' }),
            BOXLITE_RUNNER_ENV: JSON.stringify({ [key]: 'override' }),
          },
          declaration: declared,
          app: 'boxlite-app',
          stage: 'dev',
          region: 'us-east-1',
          home: 'aws',
        }),
      /BOXLITE_RUNNER_ENV/,
      key,
    )
  }
})