Skip to content

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

10.4 KB
Raw Blame
/*
 * What a deploy asks the store for, against this repository's real declaration.
 *
 * The defect this guards: `env.selectGroup.deploy` once listed every key the
 * stack could read, all required, so `valuesOfGroup` refused every deploy over
 * forty keys a stage had no reason to seed — and four it could never seed at
 * all, because an image tag and a runner binary's checksum are different on
 * every run.
 */

import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { parseBase } from 'mstage/config'
import { valuesOfGroup } from 'mstage/select-group'
import { serviceSecretsFrom, splitServiceChannels, type GroupDeclaration } from '../src/env.ts'

/**
 * The committed half alone: this asks what the repository declares, not where
 * anybody's stages live. `parseBase` is what reads it, and it returns no path
 * because it was handed one — so the path is kept here for the messages.
 */
const CONFIG_PATH = new URL('../../mstage.env.json', import.meta.url).pathname
const config = parseBase(CONFIG_PATH, readFileSync(CONFIG_PATH, 'utf8'))

const declaration: GroupDeclaration = {
  groups: config.envSelectGroup,
  optional: config.envOptional,
  where: CONFIG_PATH,
}
const requiredAppReferences = {
  CLOUD_APP_SESSION_SECRET: JSON.stringify({ address: 'arn:aws:ssm:us-east-1:123456789012:parameter/session' }),
  CLOUD_APP_IDENTITY_PRIVATE_KEY: JSON.stringify({ address: 'arn:aws:ssm:us-east-1:123456789012:parameter/identity' }),
}

/** A store holding the deploy group's required keys and nothing else. */
const minimal = {
  STACK_DOMAIN: 'dev.boxlite.ai',
  PROXY_DOMAIN: 'box.dev.boxlite.ai',
  OIDC_ISSUER_BASE_URL: 'https://auth.dev.boxlite.ai',
  IAM_PERMISSIONS_BOUNDARY_STAGE: 'dev',
  CLOUDFLARE_API_TOKEN: 'cf-token',
  CLOUDFLARE_DEFAULT_ACCOUNT_ID: 'cf-account',
  CLOUDFLARE_ZONE_ID: 'cf-zone',
  BOXLITE_STAGE_CONFIG_DIGEST: 'd'.repeat(64),
}

const narrow = (group: string, values: Record<string, string>) =>
  valuesOfGroup({
    group,
    groups: config.envSelectGroup,
    values,
    where: CONFIG_PATH,
    optional: config.envOptional[group] ?? [],
  })

test('the runner group delivers its optional JSON environment map', () => {
  const values = { BOXLITE_RUNNER_ENV: '{"BOXLITE_EXPERIMENTAL":"nested-virtualization"}' }
  assert.deepEqual(narrow('runner', values), values)
  assert.deepEqual(narrow('runner', {}), {})
})

test('a stage that seeded only the required keys can deploy', () => {
  // The reproducer. Before the split this threw, naming forty keys — including
  // four no store could ever hold.
  const resolved = narrow('deploy', minimal)
  assert.deepEqual(Object.keys(resolved).sort(), Object.keys(minimal).sort())
})

test('a required key the store lacks still stops the deploy, named', () => {
  // The invariant the split must not weaken: a silently short environment fails
  // hours later, somewhere that does not mention the key.
  const { CLOUDFLARE_ZONE_ID, ...without } = minimal
  assert.throws(() => narrow('deploy', without), /the store is missing CLOUDFLARE_ZONE_ID/)
})

test('an optional key the store does hold is carried through', () => {
  // Optional means "may be absent", never "ignored".
  const resolved = narrow('deploy', { ...minimal, BILLING_API_URL: 'https://commerce.example.com' })
  assert.equal(resolved.BILLING_API_URL, 'https://commerce.example.com')
})

test('every service group is satisfiable by its own required half', () => {
  const required = (group: string) =>
    config.envSelectGroup[group]!.filter((key) => !config.envOptional[group]!.includes(key))
  for (const group of ['api', 'proxy', 'otel-collector', 'runner']) {
    const values = Object.fromEntries(required(group).map((key) => [key, 'x']))
    assert.doesNotThrow(() => narrow(group, values), `${group} cannot be satisfied by its required keys alone`)
  }
})

test('each telemetry switch is declared by the service that reads it, and may be absent', () => {
  /*
   * The switches are the stage's to set, so they have to be declared: a key no
   * group names cannot leave the store at all — which is what left `OTEL_ENABLED`
   * derived from an `OTEL_DISABLED` nobody could seed. Optional, because a stage
   * that never set one is not a short environment: the deploy supplies the same
   * default the incumbent stack did.
   */
  const switches = {
    api: ['OTEL_ENABLED'],
    proxy: ['OTEL_LOGGING_ENABLED', 'OTEL_TRACING_ENABLED'],
    runner: ['OTEL_LOGGING_ENABLED', 'OTEL_TRACING_ENABLED'],
  }
  for (const [group, keys] of Object.entries(switches)) {
    for (const key of keys) {
      assert.ok(config.envSelectGroup[group]?.includes(key), `env.selectGroup.${group} does not name ${key}`)
      assert.ok(config.envOptional[group]?.includes(key), `env.selectGroup.${group} demands ${key} of every stage`)
    }
  }
})

test('a service reads its optional keys when present and boots without them when not', () => {
  // `serviceSecretsFrom` is the delivery side of the same question, and it has
  // to agree with the store side: a key the store was allowed to omit cannot
  // then be demanded of the deploy.
  const withoutOptional = {
    ...requiredAppReferences,
    ADMIN_API_KEY: 'a',
    ENCRYPTION_KEY: 'b',
    ENCRYPTION_SALT: 'c',
    OIDC_CLIENT_ID: 'd',
    OTEL_COLLECTOR_API_KEY: 'e',
    PROXY_API_KEY: 'f',
  }
  const bare = serviceSecretsFrom({ group: 'api', declaration, environment: withoutOptional })
  assert.deepEqual(narrow('secret', withoutOptional), requiredAppReferences)
  assert.deepEqual(Object.keys(bare).sort(), [
    'ADMIN_API_KEY',
    'CLOUD_APP_IDENTITY_PRIVATE_KEY',
    'CLOUD_APP_SESSION_SECRET',
    'ENCRYPTION_KEY',
    'ENCRYPTION_SALT',
    'OIDC_CLIENT_ID',
    'OTEL_COLLECTOR_API_KEY',
    'PROXY_API_KEY',
  ])

  const withOne = serviceSecretsFrom({
    group: 'api',
    declaration,
    environment: { ...withoutOptional, POSTHOG_API_KEY: 'ph' },
  })
  assert.equal(withOne.POSTHOG_API_KEY, 'ph')
})

test('the API receives the account-link secret a stage holds, and deploys without one', () => {
  // The Post-Login Action signs its adopt and status requests with this key
  // when it merges a person's logins into one account. A store holding it
  // under a declaration that does not name it would deploy an API answering
  // the Action 404, with nothing in the deploy saying why.
  const required = {
    ...requiredAppReferences,
    ADMIN_API_KEY: 'a',
    ENCRYPTION_KEY: 'b',
    ENCRYPTION_SALT: 'c',
    OIDC_CLIENT_ID: 'd',
    OTEL_COLLECTOR_API_KEY: 'e',
    PROXY_API_KEY: 'f',
  }
  const key = 'k'.repeat(32)
  const held = narrow('api', { ...required, OIDC_ACCOUNT_LINK_SECRET: key })
  assert.equal(serviceSecretsFrom({ group: 'api', declaration, environment: held }).OIDC_ACCOUNT_LINK_SECRET, key)

  const unheld = narrow('api', required)
  assert.equal(
    serviceSecretsFrom({ group: 'api', declaration, environment: unheld }).OIDC_ACCOUNT_LINK_SECRET,
    undefined,
  )
})

test('a required service key that never arrived still stops the deploy', () => {
  assert.throws(
    () => serviceSecretsFrom({ group: 'api', declaration, environment: { ADMIN_API_KEY: 'a' } }),
    /ENCRYPTION_KEY, ENCRYPTION_SALT, OIDC_CLIENT_ID, OTEL_COLLECTOR_API_KEY, PROXY_API_KEY, CLOUD_APP_SESSION_SECRET, CLOUD_APP_IDENTITY_PRIVATE_KEY must reach the deploy/,
  )
})

test('splitting channels still works when an optional key is simply absent', () => {
  // The split reads the marker group; an absent key must not become an entry
  // with an undefined value, which is what would reach a container as "".
  const { values, addresses } = splitServiceChannels({
    delivered: serviceSecretsFrom({
      group: 'proxy',
      declaration,
      environment: { PROXY_API_KEY: 'k' },
    }),
    declaration,
    home: 'aws',
  })
  assert.deepEqual(values, { PROXY_API_KEY: 'k' })
  assert.deepEqual(addresses, {})
})

test('a key the API compares against is held by the API too, or the caller is refused', () => {
  /*
   * The API authenticates its first-party callers by comparing a bearer token
   * against its *own* copy of their key — `api-key.strategy.ts` is a chain of
   * `if (thisApiKey && thisApiKey === token)` branches. So each of these keys is
   * one value that has to reach two workloads: the caller, which sends it, and
   * the API, which compares it.
   *
   * A key named for the caller alone leaves the API's copy undefined, the
   * comparison short-circuits, and the request falls through to whatever comes
   * after the branch. Both instances below were that, and both were silent:
   *
   *   PROXY_API_KEY — every box request answered `failed to get runner info:
   *   Invalid credentials`, a 400 from the proxy for what was a 401 at the API,
   *   with `/api/health` still green.
   *
   *   OTEL_COLLECTOR_API_KEY — the collector's exports answered 401 while the
   *   collector itself looked healthy, so a stage simply had no telemetry.
   *
   * Asserted against the real declaration rather than a fixture: the defect was
   * the declaration's contents, so a fixture would have agreed with itself.
   *
   * The list is written out rather than derived, and it is shorter than the
   * strategy's branch list on purpose. `api-key.strategy.ts` compares four keys;
   * the other two belong to the health-check and billing services, which this
   * stack does not deploy — `mbuild.config.json` builds `api`, `proxy`,
   * `otel-collector` and `registry-proxy`, and nothing under `apps/infra` names
   * either key. So they have no caller group to be named for, and demanding one
   * would fail every stage over a service that is not there.
   *
   * The registry proxy is deployed and is absent here on purpose: it holds no
   * key of its own. It asks the API about a caller by presenting that caller's
   * runner key, so the strategy branch it reaches is the runner's, which is
   * seeded by the stack rather than by a group.
   *
   * What that costs is worth stating: a fifth branch, or a caller this stack
   * starts deploying, does not trip this test. It has to be added here, and
   * this paragraph is the only thing that says so.
   */
  const compared = [
    { caller: 'proxy', key: 'PROXY_API_KEY' },
    { caller: 'otel-collector', key: 'OTEL_COLLECTOR_API_KEY' },
  ]
  for (const { caller, key } of compared) {
    for (const group of [caller, 'api']) {
      assert.ok(
        config.envSelectGroup[group]?.includes(key),
        `env.selectGroup.${group} does not name ${key}, so the ${group} cannot hold the key the other side compares against`,
      )
    }
  }
})