The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
/*
* The composition root, driven by recording fakes.
*
* `stack/index.ts` names no cloud, which is exactly what makes this possible: a
* bundle of fakes satisfies `StackProviders` as well as either real bundle
* does, so the order the modules go in and what each one is handed can be
* checked without an account, a network, or either engine.
*
* What is checked here is the wiring — that a module is handed the handles it
* depends on, that the stack's own names win over the store's, and that a name
* carried by two channels is refused. What is not checked is any resource's
* arguments; those live in the provider bundles, which need their cloud.
*/
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
import { parseBase } from 'mstage/config'
import { valuesOfGroup } from 'mstage/select-group'
import { deployStack, type StackInputs, type StackProviders } from '../stack/index.ts'
import { apiEnvironmentFrom } from '../src/api-environment.ts'
import { parseDeployConfig, type DeployConfig } from '../src/config.ts'
import type { ClickHouse } from '../stack/clickhouse.ts'
/** A resolved value, in the shape the contracts describe. */
const out = <T>(value: T): any => ({ apply: (fn: (v: T) => unknown) => out(fn(value)), __output: value })
/** What a fake handed back, unwrapped. */
const read = (value: any): unknown =>
value && typeof value === 'object' && '__output' in value ? value.__output : value
const config: DeployConfig = parseDeployConfig(
'/repo/apps/infra/mdeploy.config.json',
JSON.stringify({
database: { name: 'boxlite', size: 'small', highlyAvailable: false, backupRetentionDays: 7, protected: false },
cache: { size: 'small', clustered: false, encryptInTransit: true },
storage: { volumePrefix: 'boxlite-volume', versioning: true },
clickhouse: {
mode: 'self-hosted',
database: 'otel',
writerUsername: 'otel_writer',
readerUsername: 'otel_reader',
instanceSize: 'medium',
dataGb: 50,
},
runners: { size: 'large', rootDiskGb: 100 },
alarms: {
apiServerErrors: { threshold: 1, periods: 1 },
proxyUnhealthyTargets: { threshold: 1, periods: 2 },
runnersUnreachable: { threshold: 1, periods: 3 },
runnersDiskExpansionFailing: { threshold: 3, periods: 1 },
runnersDiskPressureCritical: { threshold: 1, periods: 2 },
},
}),
)
const inputs = (overrides: Partial<StackInputs> = {}): StackInputs => ({
stage: 'dev',
tag: 'a'.repeat(40),
domain: 'dev.boxlite.ai',
proxyDomain: 'box.dev.boxlite.ai',
proxyProtocol: 'http',
proxyTemplateUrl: 'http://box.dev.boxlite.ai',
internetEgress: true,
senderDomain: 'mail.dev.boxlite.ai',
userDomain: { domain: 'apps.example', dnsZoneId: 'user-zone' },
runnerBinary: {
tarballUrl: 'https://example.invalid/runner-v0.10.0.tar.gz',
checksumUrl: 'https://example.invalid/runner-v0.10.0.tar.gz.sha256',
tarballName: 'runner-v0.10.0.tar.gz',
transport: 'https',
source: 'release',
identity: '0.10.0',
},
runnerFleet: [{ resourceName: 'Runner', nameTag: 'boxlite-app-dev-runner', controlPlaneRunnerName: 'default' }],
apiEnvironment: {},
apiSecrets: {},
proxyEnvironment: {},
proxySecrets: {},
// The collector's key is required in its group, so an input shape without it
// is not one a deploy can produce — and the stack refuses it rather than
// shipping a collector that authenticates to the API as nobody.
collectorEnvironment: { OTEL_COLLECTOR_API_KEY: 'otel-key' },
collectorSecrets: {},
runnerEnvironment: {},
runnerSecrets: {},
clickHouseRetentionHours: null,
filestoreProjects: [],
...overrides,
})
test('the API and Runner receive the endpoints published by their own Secret Server roles', () => {
const { providers, seen } = bundle()
const writeUrl = out('https://write.run.app')
const fetchUrl = out('https://fetch.run.app')
const deployFetch = () => ({ url: fetchUrl, enrolledInstanceIds: out(['12345']) })
deployStack({
providers: { ...providers, secretServer: () => ({ writeUrl, deployFetch }) },
config,
inputs: { ...inputs(), runnerEnvironment: { SECRET_SERVER_URL: 'https://stale.example.test' } },
})
assert.equal(seen.api.request.environment.SECRET_SERVER_URL, writeUrl)
assert.equal(seen.runners.request.environment.SECRET_SERVER_URL, undefined)
assert.equal(seen.runners.request.deploySecretFetch, deployFetch)
})
test('filestore projects become the final API capability', () => {
const { providers, seen } = bundle()
deployStack({
providers,
config,
inputs: inputs({ filestoreProjects: ['zeta-project', 'alpha-project'] }),
})
assert.deepEqual(seen.api.request.capabilities.at(-1), {
kind: 'read-filestore-instances',
projects: ['zeta-project', 'alpha-project'],
})
})
test('retention is resolved once, and only a self-hosted ClickHouse accepts one', () => {
const retentionSeen = (clickHouseRetentionHours: number | null, mode = config.clickhouse.mode) => {
const providers = bundle()
deployStack({
providers: providers.providers,
config: { ...config, clickhouse: { ...config.clickhouse, mode } },
inputs: inputs({ clickHouseRetentionHours }),
})
return providers.seen.clickhouse.request.retentionHours
}
assert.equal(retentionSeen(168), 168)
assert.equal(retentionSeen(null), 720)
for (const mode of ['managed', 'disabled'] as const) {
assert.equal(retentionSeen(null, mode), 720)
assert.throws(
() => retentionSeen(168, mode),
/CLICKHOUSE_RETENTION_HOURS cannot be set when deploy.clickhouse.mode is/,
)
}
})
/**
* A fleet of the given control-plane names, shaped as `runnerFleetFrom` shapes one.
*
* The first slot keeps the resource name `Runner`; every later one is numbered.
* Copied in that detail on purpose — a test that invented its own naming would
* pass while the real fleet renamed a host, which replaces a machine.
*/
const fleetOf = (...names: string[]) =>
names.map((controlPlaneRunnerName, index) =>
index === 0
? { resourceName: 'Runner', nameTag: 'boxlite-app-dev-runner', controlPlaneRunnerName }
: {
resourceName: `Runner-runner-${index + 1}`,
nameTag: `boxlite-app-dev-runner-${index + 1}`,
controlPlaneRunnerName,
},
)
const clickHouseFake = (active: boolean): ClickHouse =>
active
? {
active: true,
mode: 'self-hosted',
url: out('http://10.0.0.9:8123'),
database: 'otel',
writer: { username: 'otel_writer', passwordRef: out('writer-ref'), credentialVersion: out('v1') },
reader: { username: 'otel_reader', passwordRef: out('reader-ref'), credentialVersion: out('v1') },
id: out('i-clickhouse'),
ready: ['clickhouse'],
}
: { active: false, mode: 'disabled' }
/**
* A bundle that records what each module was handed.
*
* Every entry answers with a plausible handle rather than a stub that throws,
* because the stack reads these — `api.address` reaches the proxy and the
* runner, `collector.otlpUrl` reaches three workloads — and a fake that
* returned nothing would pass a wiring check it never exercised.
*/
const bundle = ({
clickhouse = true,
registryCredentials = true,
registryProxy = true,
checkpoints = false,
servesUserDomain = true,
resizeRunnerDisks = true,
}: {
clickhouse?: boolean
registryCredentials?: boolean
registryProxy?: boolean
checkpoints?: boolean
servesUserDomain?: boolean
resizeRunnerDisks?: boolean
} = {}) => {
const seen: Record<string, any> = {}
const order: string[] = []
const record = (name: string, value: any) => {
order.push(name)
seen[name] = value
return value
}
const network = {
binding: { cloud: 'aws' as const, cidr: out('10.0.0.0/16') },
placementFor: (role: string) => ({
cloud: 'aws' as const,
exposure: role === 'runner' ? 'egress-only-public' : 'private',
role,
}),
ready: ['network-rules'],
}
const storage = {
name: out('boxlite-dev-storage'),
binding: { cloud: 'aws' as const, credentialVending: { roleName: 'r', roleArn: out('arn:role') } },
checkpoints: checkpoints
? {
active: true,
bucket: out('boxlite-dev-checkpoints'),
archivePrefix: out('gs://boxlite-dev-checkpoints/checkpoints/'),
}
: { active: false },
ready: [],
}
const database = {
connection: { host: out('db.internal'), port: out('5432'), username: out('boxlite'), database: out('boxlite') },
binding: { cloud: 'aws' as const, passwordRef: out('db-ref'), clientGrant: out('sg-db') },
id: out('db-1'),
ready: ['db'],
}
const cache = {
connection: { host: out('cache.internal'), port: out('6379') },
binding: { cloud: 'aws' as const, passwordRef: out('cache-ref'), clientGrant: out('sg-cache') },
id: out('cache-1'),
ready: ['cache'],
}
const providers = {
images: (request: any) =>
record('images', {
api: out(`registry/${request.tag}-api`),
proxy: out(`registry/${request.tag}-proxy`),
'otel-collector': out(`registry/${request.tag}-otel`),
'registry-proxy': out(`registry/${request.tag}-registry-proxy`),
'secret-server': out(`registry/${request.tag}-secret-server`),
}),
network: (request: any) => record('network', { ...network, request }),
storage: (request: any) => record('storage', { ...storage, request }),
cluster: (input: any) => (request: any) =>
record('cluster', {
input,
request,
hostFor: (role: string) => ({ cloud: 'aws' as const, role }),
ready: input.network.ready,
}),
database: (input: any) => (request: any) => record('database', { ...database, input, request }),
cache: (input: any) => (request: any) => record('cache', { ...cache, input, request }),
clickhouse: (input: any) => (request: any) =>
record('clickhouse', { ...clickHouseFake(clickhouse), input, request }),
mail: (request: any) =>
record('mail', {
sending: Boolean(request.senderDomain),
verified: true,
host: 'smtp.invalid',
port: '465',
senderAddress: `no-reply@${request.senderDomain}`,
ready: ['mail'],
request,
}),
collector: (input: any) => (request: any) =>
record('collector', { input, request, otlpUrl: out('http://collector:4318'), ready: ['collector'] }),
api: (input: any) => (request: any) =>
record('api', {
input,
request,
url: out('https://dev.boxlite.ai'),
address: out('https://api.dev.boxlite.ai'),
identity: out('arn:task-role'),
metricTarget: out('app/api/1'),
ready: ['api'],
}),
edge: (input: any) => (request: any) =>
record('edge', {
input,
request,
url: out('https://box.dev.boxlite.ai'),
metricTarget: out('net/proxy/1'),
ready: ['edge'],
}),
servesUserDomain: () => servesUserDomain,
resizeRunnerDisks: () => resizeRunnerDisks,
registryProxy: (input: any) => (request: any) =>
record(
'registryProxy',
registryProxy
? {
input,
request,
active: true,
url: out('https://registry-proxy-123.run.app'),
ready: ['registryProxy'],
}
: { input, request, active: false },
),
registryCredentials: () =>
record(
'registryCredentials',
registryCredentials
? {
active: true,
binding: {
cloud: 'gcp',
createRole: out('projects/p/roles/creator'),
writeRole: out('projects/p/roles/writer'),
condition: { title: 't', description: 'd', expression: 'resource.name.startsWith("x")' },
},
}
: { active: false },
),
// Named by what it mints, so a test can tell one host's token from another's
// — which is the whole property `RunnerAssignment` exists to hold.
mintRunnerToken: (name: string) => `minted:${name}`,
runners: (input: any) => (request: any) =>
record('runners', { input, request, ids: [out('i-runner')], ready: ['runners'] }),
alarms: (input: any) => (request: any) => record('alarms', { input, request }),
} as unknown as StackProviders
return { providers, seen, order }
}
test('every module is handed the modules it depends on, and nothing else builds first', () => {
const { providers, order } = bundle()
deployStack({ providers, config, inputs: inputs() })
// The graph, read back out of what each provider was handed.
assert.ok(order.indexOf('network') < order.indexOf('cluster'), 'the cluster is placed in the network')
assert.ok(order.indexOf('database') < order.indexOf('api'), 'the API queries tables')
assert.ok(order.indexOf('collector') < order.indexOf('api'), 'the API emits to the collector')
assert.ok(order.indexOf('api') < order.indexOf('edge'), 'the proxy resolves a box through the API')
assert.ok(order.indexOf('api') < order.indexOf('runners'), 'a runner registers with the API')
assert.ok(order.indexOf('runners') < order.indexOf('alarms'), 'an alarm watches something that exists')
assert.equal(order.at(-1), 'alarms', 'nothing waits on an alarm')
})
test('the runner is placed directly, because it is a machine rather than a task', () => {
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
// No host: `cluster.ts` says why, and a runner handed one would mean a
// cluster with no tasks in it on AWS and nothing at all on GCP.
assert.equal(seen.runners.input.host, undefined)
assert.ok(seen.runners.input.network, 'it takes its placement from the network instead')
})
test('parsed stage sizes reach the API and runner providers', () => {
const { providers, seen } = bundle()
const settings = Object.fromEntries(Object.entries(config).filter(([key]) => key !== 'path' && key !== 'root'))
const sizedConfig = parseDeployConfig(
config.path,
JSON.stringify({
...settings,
api: { minInstances: 0, instance: { cpu: 2, memoryMiB: 2048 } },
runners: { ...config.runners, dataDiskGb: 2048 },
}),
)
deployStack({ providers, config: sizedConfig, inputs: inputs() })
assert.deepEqual(seen.api.request.instance, { cpu: 2, memoryMiB: 2048 })
assert.equal(seen.api.request.minInstances, 0)
assert.equal(seen.runners.request.dataDiskGb, 2048)
})
test('the stack’s own names win over a stale copy in the store', () => {
const { providers, seen } = bundle()
deployStack({
providers,
config,
inputs: inputs({ apiEnvironment: { DB_HOST: 'yesterdays-database.invalid', OIDC_AUDIENCE: 'boxlite' } }),
})
const environment = seen.api.request.environment
assert.equal(
read(environment.DB_HOST),
'db.internal',
'the database this deploy built, not the one the store remembers',
)
assert.equal(environment.OIDC_AUDIENCE, 'boxlite', 'and a name only the store decides is carried through')
})
test('checkpoint admission stays off until the API environment explicitly enables it', () => {
for (const enabled of [undefined, 'false', 'true']) {
const { providers, seen } = bundle()
deployStack({
providers,
config,
inputs: inputs({ apiEnvironment: enabled === undefined ? {} : { CHECKPOINTS_ENABLED: enabled } }),
})
assert.equal(seen.api.request.environment.CHECKPOINTS_ENABLED, enabled ?? 'false')
assert.equal(seen.api.request.environment.MEMORY_CHECKPOINTS_ENABLED, 'false')
}
})
test('memory checkpoint admission stays off until the API environment explicitly enables it', () => {
for (const enabled of [undefined, 'false', 'true']) {
const { providers, seen } = bundle()
deployStack({
providers,
config,
inputs: inputs({ apiEnvironment: enabled === undefined ? {} : { MEMORY_CHECKPOINTS_ENABLED: enabled } }),
})
assert.equal(seen.api.request.environment.MEMORY_CHECKPOINTS_ENABLED, enabled ?? 'false')
}
})
test('the API is told the origin a client composes a box URL from', () => {
/*
* `ConfigurationDto` takes `proxy.templateUrl` with `getOrThrow`
* (`apps/api/src/config/dto/configuration.dto.ts`), so a container without
* `PROXY_TEMPLATE_URL` answers `/api/config` with a 500. The box proxy reads
* that exact route before it forwards a byte — `get BoxLite API config`, ten
* attempts, then it exits — so the whole edge stays down while the API's own
* `/api/health` keeps answering 200 and the deploy reports success.
*
* The incumbent path carries it (`stack/api.ts`); this one dropped it, and
* `PROXY_TEMPLATE_URL` appeared nowhere under `mdeploy/` at all. Observed on
* `dev2`: two proxy hosts the balancer never called healthy, with nothing in
* the apply having failed.
*/
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs({ proxyTemplateUrl: 'https://box.dev.boxlite.ai' }) })
assert.equal(read(seen.api.request.environment.PROXY_TEMPLATE_URL), 'https://box.dev.boxlite.ai')
})
test('the API, the proxy and the edge are told one user domain, or none at all', () => {
// The API mints `demo.<userDomain>` URLs, the proxy resolves them and the edge
// serves the wildcard in the domain's own zone: one answer from the stage, or
// every half stays silent so no URL is handed out that nothing answers.
const served = bundle()
deployStack({ providers: served.providers, config, inputs: inputs() })
assert.equal(read(served.seen.api.request.environment.PROXY_APP_DOMAIN), 'apps.example')
assert.equal(read(served.seen.edge.request.environment.PROXY_APP_DOMAIN), 'apps.example')
assert.deepEqual(served.seen.edge.request.userDomain, { domain: 'apps.example', dnsZoneId: 'user-zone' })
const unset = bundle()
deployStack({ providers: unset.providers, config, inputs: inputs({ userDomain: null }) })
assert.ok(!('PROXY_APP_DOMAIN' in unset.seen.api.request.environment))
assert.ok(!('PROXY_APP_DOMAIN' in unset.seen.edge.request.environment))
assert.equal(unset.seen.edge.request.userDomain, null)
})
test('a user domain on a cloud whose edge serves none is refused, not dropped', () => {
const { providers } = bundle({ servesUserDomain: false })
assert.throws(
() => deployStack({ providers, config, inputs: inputs() }),
/STACK_USER_DOMAIN is apps\.example, and this cloud's edge serves no user domain/,
)
deployStack({ providers, config, inputs: inputs({ userDomain: null }) })
})
test('a name the store delivers as an address and the stack also carries is refused', () => {
// Two entries for one variable: an ECS task takes the last one written and a
// Cloud Run revision refuses the pair, so the divergence is refused here
// where every channel is known.
const { providers } = bundle()
assert.throws(
() => deployStack({ providers, config, inputs: inputs({ apiSecrets: { DB_PASSWORD: 'arn:some-secret' } }) }),
/DB_PASSWORD would reach the API twice/,
)
assert.throws(
() => deployStack({ providers, config, inputs: inputs({ apiSecrets: { DB_HOST: 'arn:some-secret' } }) }),
/DB_HOST would reach the API twice/,
)
})
test('each workload reads its own group and no other', () => {
const { providers, seen } = bundle()
deployStack({
providers,
config,
inputs: inputs({
apiSecrets: { OIDC_CLIENT_SECRET: 'arn:api' },
proxySecrets: { PROXY_API_KEY: 'arn:proxy' },
// Cleared, because the store puts a key on one channel or the other: with
// it on both, `assertOneChannelPerName` refuses the pair — which is the
// guard working, not a fixture detail.
collectorEnvironment: {},
collectorSecrets: { OTEL_COLLECTOR_API_KEY: 'arn:otel' },
runnerSecrets: { DEFAULT_RUNNER_API_KEY: 'arn:runner' },
}),
})
assert.deepEqual(Object.keys(seen.api.request.secrets), ['OIDC_CLIENT_SECRET'])
assert.deepEqual(Object.keys(seen.edge.request.secrets), ['PROXY_API_KEY'])
// Two names, one secret: the collector reads `BOXLITE_API_KEY` and the API
// compares against `OTEL_COLLECTOR_API_KEY`. See the rename's own test below.
assert.deepEqual(Object.keys(seen.collector.request.secrets), ['OTEL_COLLECTOR_API_KEY', 'BOXLITE_API_KEY'])
assert.deepEqual(Object.keys(seen.runners.request.secrets), ['DEFAULT_RUNNER_API_KEY'])
})
test('the collector is given its own name for the key, on whichever channel carried it', () => {
/*
* One value, two workloads, two names: the collector sends it as a bearer
* token and reads it from `BOXLITE_API_KEY`, while the API compares against
* its copy of `OTEL_COLLECTOR_API_KEY`. The store declares the one name, so
* the rename happens here.
*
* Both channels, because the store decides which one: a key marked in
* `env.selectGroup.secret` arrives as an address in `collectorSecrets`
* instead of as a value. A rename that read only the value channel shipped a
* collector with no `BOXLITE_API_KEY` on that path — and silently, because
* `apps/otel-collector/config.yaml` defaults it to a literal that
* authenticates as nobody: every export answered 401 while the collector
* looked healthy.
*/
const asValue = bundle()
deployStack({
providers: asValue.providers,
config,
inputs: inputs({ collectorEnvironment: { OTEL_COLLECTOR_API_KEY: 'otel-key' }, collectorSecrets: {} }),
})
assert.equal(asValue.seen.collector.request.environment.BOXLITE_API_KEY, 'otel-key')
assert.equal(asValue.seen.collector.request.secrets.BOXLITE_API_KEY, undefined, 'a value stays a value')
const asAddress = bundle()
deployStack({
providers: asAddress.providers,
config,
inputs: inputs({ collectorEnvironment: {}, collectorSecrets: { OTEL_COLLECTOR_API_KEY: 'arn:otel' } }),
})
assert.equal(asAddress.seen.collector.request.secrets.BOXLITE_API_KEY, 'arn:otel', 'two names, one secret')
assert.equal(
asAddress.seen.collector.request.environment.BOXLITE_API_KEY,
undefined,
'an address must not be flattened into a value the task definition would carry',
)
})
test('a collector the key reached on neither channel is refused, not shipped', () => {
// Required in its group, so this means the declaration changed rather than a
// stage forgetting something. The alternative is a collector that starts,
// reports healthy, and is answered 401 forever.
assert.throws(
() =>
deployStack({
providers: bundle().providers,
config,
inputs: inputs({ collectorEnvironment: {}, collectorSecrets: {} }),
}),
/OTEL_COLLECTOR_API_KEY reached neither the collector's values nor its secrets/,
)
})
test('the API and the first host are handed the same minted token', () => {
// Pairing is token-based: the API seeds the first runner's row from
// DEFAULT_RUNNER_API_KEY and that host presents the same value as
// BOXLITE_RUNNER_TOKEN. Two different values is a host that boots, is
// answered 401 on every call it makes, and never reports in — which is what a
// provider minting its own token after the API was built would produce.
const { providers, seen } = bundle()
deployStack({
providers,
config,
inputs: inputs({ runnerFleet: fleetOf('default', 'runner-2'), apiEnvironment: { ADMIN_API_KEY: 'admin' } }),
})
const forApi = seen.api.request.environment.DEFAULT_RUNNER_API_KEY
const forHost = seen.runners.request.fleet[0].token
assert.equal(forApi, forHost, 'the API seeds the row this host authenticates against')
assert.equal(forApi, 'minted:RunnerToken-default')
})
test('every host gets its own token, named after the row it will hold', () => {
// A shared token makes two hosts one identity to the control plane: whichever
// reported last owns the row, and the other's work is attributed to it. The
// resource name follows the control-plane name rather than the index, so
// growing the fleet does not renumber tokens already registered.
const { providers, seen } = bundle()
deployStack({
providers,
config,
inputs: inputs({
runnerFleet: fleetOf('default', 'runner-2', 'runner-3'),
apiEnvironment: { ADMIN_API_KEY: 'admin' },
}),
})
const tokens = seen.runners.request.fleet.map((assignment: any) => assignment.token)
assert.deepEqual(tokens, ['minted:RunnerToken-default', 'minted:RunnerToken-runner-2', 'minted:RunnerToken-runner-3'])
assert.equal(new Set(tokens).size, tokens.length, 'two hosts sharing a token are one identity to the control plane')
})
test('a stage with no telemetry runs the BoxLite exporter alone', () => {
// A collector told to write to a ClickHouse that does not exist retries every
// batch forever, so this is not cosmetic.
const off = bundle({ clickhouse: false })
deployStack({ providers: off.providers, config, inputs: inputs() })
assert.equal(off.seen.collector.request.exporters, '[boxlite_exporter]')
assert.equal(off.seen.api.request.environment.CLICKHOUSE_URL, undefined, 'and the API is told nothing about one')
assert.ok(
!off.seen.api.request.capabilities.some((capability: any) => capability.kind === 'read-telemetry'),
'nor granted a permission it could never use',
)
const on = bundle({ clickhouse: true })
deployStack({ providers: on.providers, config, inputs: inputs() })
assert.equal(on.seen.collector.request.exporters, '[boxlite_exporter,clickhouse]')
assert.equal(read(on.seen.api.request.environment.CLICKHOUSE_USERNAME), 'otel_reader', 'the API reads, never writes')
assert.equal(read(on.seen.collector.request.environment.CLICKHOUSE_USERNAME), 'otel_writer')
})
test('the proxy is told to export, and a stage that wants it quiet says so', () => {
/*
* `cmd/proxy/config/config.go` gives neither switch a default, so an unset Go
* bool is false and the exporter is never built: a proxy that is healthy,
* pointed at the collector, and silent. The incumbent stack defaulted both to
* `true` and the runner's boot script still does.
*/
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
assert.equal(read(seen.edge.request.environment.OTEL_LOGGING_ENABLED), 'true')
assert.equal(read(seen.edge.request.environment.OTEL_TRACING_ENABLED), 'true')
const quiet = bundle()
deployStack({
providers: quiet.providers,
config,
inputs: inputs({ proxyEnvironment: { OTEL_LOGGING_ENABLED: 'false', OTEL_TRACING_ENABLED: 'false' } }),
})
assert.equal(read(quiet.seen.edge.request.environment.OTEL_LOGGING_ENABLED), 'false', 'the store has to win')
assert.equal(read(quiet.seen.edge.request.environment.OTEL_TRACING_ENABLED), 'false')
})
test('each consumer is told the endpoint under the name it actually reads', () => {
/*
* Two programs, two contracts: the collector's ClickHouse exporter reads
* `CLICKHOUSE_ENDPOINT` and the API reads `CLICKHOUSE_URL`. One name for both
* is not a container that fails to start — the collector falls back to its own
* `clickhouse-disabled.invalid` default and retries every batch forever, with
* the database running and the deploy green.
*/
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
assert.equal(read(seen.collector.request.environment.CLICKHOUSE_ENDPOINT), 'http://10.0.0.9:8123')
assert.equal(seen.collector.request.environment.CLICKHOUSE_URL, undefined, 'the collector reads no such name')
assert.equal(read(seen.api.request.environment.CLICKHOUSE_URL), 'http://10.0.0.9:8123')
assert.equal(seen.api.request.environment.CLICKHOUSE_ENDPOINT, undefined, 'nor does the API read the other')
})
test('a stage that sends no mail carries no SMTP host, which is what disables it', () => {
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs({ senderDomain: null }) })
assert.equal(seen.api.request.environment.SMTP_HOST, undefined)
assert.equal(seen.mail.request.senderDomain, null)
})
test('the API is granted exactly the capabilities its storage supports', () => {
const { providers, seen } = bundle()
void seen
deployStack({ providers, config, inputs: inputs() })
assert.deepEqual(seen.api.request.capabilities.map((capability: any) => capability.kind).sort(), [
'list-own-bucket',
'manage-app-source',
'manage-volume-buckets',
'read-telemetry',
'resize-runner-disks',
'vend-volume-credentials',
'write-registry-credentials',
])
})
test('adding the resize grant does not shift the checkpoint grant an existing stage already holds', () => {
// Providers name each grant by its index; a grant inserted ahead of others
// would move them to new resources, and on GCP that deletes the bindings.
const kinds = (deployed: ReturnType<typeof bundle>) =>
deployed.seen.api.request.capabilities.map((capability: any) => capability.kind)
const before = bundle({ checkpoints: true, resizeRunnerDisks: false })
deployStack({ providers: before.providers, config, inputs: inputs() })
const after = bundle({ checkpoints: true, resizeRunnerDisks: true })
deployStack({ providers: after.providers, config, inputs: inputs() })
assert.equal(kinds(before).at(-1), 'manage-app-source')
assert.deepEqual(kinds(after), [...kinds(before).slice(0, -1), 'resize-runner-disks', 'manage-app-source'])
})
test('checkpoints are on only where storage keeps a bucket for them, for the API and the hosts alike', () => {
const kept = bundle({ checkpoints: true })
deployStack({ providers: kept.providers, config, inputs: inputs() })
assert.equal(kept.seen.api.request.environment.CHECKPOINT_ARCHIVE_PREFIX, kept.seen.storage.checkpoints.archivePrefix)
const grant = kept.seen.api.request.capabilities.find(
(capability: any) => capability.kind === 'manage-checkpoint-archives',
)
assert.equal(grant?.checkpoints.bucket, kept.seen.storage.checkpoints.bucket)
// The hosts write the archives the API deletes, so they are handed the same bucket.
assert.equal(kept.seen.runners.request.checkpointBucket, kept.seen.storage.checkpoints.bucket)
/*
* A cloud with no checkpoint store (AWS, reserved) gets no variable, no grant
* and no bucket for its hosts; the API then reports checkpoints off.
*/
const none = bundle()
deployStack({ providers: none.providers, config, inputs: inputs() })
assert.equal('CHECKPOINT_ARCHIVE_PREFIX' in none.seen.api.request.environment, false)
assert.equal(
none.seen.api.request.capabilities.some((capability: any) => capability.kind === 'manage-checkpoint-archives'),
false,
)
assert.equal(none.seen.runners.request.checkpointBucket, null)
})
test('the API is granted the disk resize only where a data disk exists to grow', () => {
// The AWS-shaped bundle keeps no per-runner data disk, and its provider
// refuses the capability outright — so the grant must be asked for and not
// assumed. A grant bounded to resources the cloud never creates would be a
// permission that silently matched nothing.
const { providers, seen } = bundle({ resizeRunnerDisks: false })
deployStack({ providers, config, inputs: inputs() })
const kinds = seen.api.request.capabilities.map((capability: any) => capability.kind)
assert.equal(kinds.includes('resize-runner-disks'), false)
})
test('the API writes registry passwords only where a store keeps them, and is told which store', () => {
const kept = bundle()
deployStack({ providers: kept.providers, config, inputs: inputs() })
assert.ok(kept.order.indexOf('registryCredentials') < kept.order.indexOf('api'), 'the grant names the store')
assert.equal(kept.seen.api.request.environment.REGISTRY_SECRET_STORE, 'gcp')
/*
* No store, no grant and no variable. The API then leaves private registries
* off rather than accepting a password it has nowhere to put.
*/
const none = bundle({ registryCredentials: false })
deployStack({ providers: none.providers, config, inputs: inputs() })
const kinds = none.seen.api.request.capabilities.map((capability: any) => capability.kind)
assert.equal(kinds.includes('write-registry-credentials'), false)
assert.equal('REGISTRY_SECRET_STORE' in none.seen.api.request.environment, false)
})
test('what the deploy reports is what a post-deploy check needs to read', () => {
const { providers } = bundle()
const outputs = deployStack({ providers, config, inputs: inputs() })
assert.equal(read(outputs.apiUrl), 'https://dev.boxlite.ai')
assert.equal(read(outputs.proxyUrl), 'https://box.dev.boxlite.ai')
assert.equal(read(outputs.databaseId), 'db-1')
assert.equal(read(outputs.storageName), 'boxlite-dev-storage')
assert.equal(outputs.runnerIds.length, 1)
assert.notEqual(outputs.clickHouseId, null)
})
test('a commit whose images were never published fails before anything is built', () => {
const { providers } = bundle()
const withoutProxy = {
...providers,
images: () => ({ api: out('a'), 'otel-collector': out('c'), 'registry-proxy': out('r') }),
} as StackProviders
assert.throws(
() => deployStack({ providers: withoutProxy, config, inputs: inputs() }),
/mbuild published no proxy image for this commit/,
)
})
// ── the registry proxy ──────────────────────────────────────────────────────
test('the registry proxy is built before the API, which writes its host into private refs', () => {
/*
* The API hands a runner a private image as a ref under the proxy's host, so
* it needs that host when it is built. The proxy asks the API about every
* caller, but by `api.<domain>`, which the stage's domain fixes before either
* exists. The gap that leaves is a first deploy's, before anything has a box
* to pull for; on every later one the API is already answering.
*/
const { providers, order, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
assert.ok(order.indexOf('registryProxy') < order.indexOf('api'), 'the API is handed the proxy host')
assert.equal(seen.registryProxy.input.dependsOn.includes('api'), false, 'so it cannot wait for the API')
assert.equal(read(seen.api.request.environment.REGISTRY_PROXY_HOST), 'registry-proxy-123.run.app')
})
test('the API and runners agree on the proxy host, and only the proxy gets the anonymous list', () => {
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
assert.equal(read(seen.runners.request.registryProxyHost), 'registry-proxy-123.run.app')
assert.equal('REGISTRY_PROXY_UPSTREAM_HOSTS' in seen.api.request.environment, false)
assert.equal(
seen.registryProxy.request.environment.REGISTRY_PROXY_UPSTREAM_HOSTS,
'ghcr.io,docker.io,quay.io,gcr.io,us.gcr.io,eu.gcr.io,asia.gcr.io',
)
})
test('a stage with no registry proxy hands its host to nobody', () => {
const { providers, seen } = bundle({ registryProxy: false })
deployStack({ providers, config, inputs: inputs() })
assert.equal('REGISTRY_PROXY_HOST' in seen.api.request.environment, false)
assert.equal(seen.runners.request.registryProxyHost, null)
})
test('a stored anonymous upstream list reaches the registry proxy', () => {
const key = 'REGISTRY_PROXY_UPSTREAM_HOSTS'
const path = fileURLToPath(new URL('../../mstage.env.json', import.meta.url))
const stage = parseBase(path, readFileSync(path, 'utf8'))
const optional = stage.envOptional.deploy ?? []
const required = Object.fromEntries(
stage.envSelectGroup.deploy.filter((name) => !optional.includes(name)).map((name) => [name, 'test-fixture']),
)
for (const [configured, expected] of [
[' GHCR.IO , , Registry.Example.com ', 'ghcr.io,registry.example.com'],
[' , ', 'ghcr.io,docker.io,quay.io,gcr.io,us.gcr.io,eu.gcr.io,asia.gcr.io'],
]) {
const selected = valuesOfGroup({
group: 'deploy',
groups: stage.envSelectGroup,
optional,
where: path,
values: {
...required,
STACK_DOMAIN: 'dev.boxlite.ai',
OIDC_ISSUER_BASE_URL: 'https://auth.dev.boxlite.ai',
[key]: configured,
},
})
assert.equal(selected[key], configured, 'mstage selects the stored override')
const { environment: apiEnvironment } = apiEnvironmentFrom({
environment: selected,
declaration: { groups: { deploy: stage.envSelectGroup.deploy, api: [] }, where: path },
region: 'asia-southeast1',
stage: 'dev',
home: 'gcp',
})
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs({ apiEnvironment }) })
assert.equal(key in seen.api.request.environment, false)
assert.equal(seen.registryProxy.request.environment[key], expected)
}
})
test('the registry proxy is handed the API as its control plane', () => {
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
// Spelled as the runner's unit spells it: the API client's paths sit under
// `/api`, and the balancer's rewrite is not a thing to lean on.
assert.equal(read(seen.registryProxy.request.environment.BOXLITE_API_URL), 'https://api.dev.boxlite.ai/api')
})
test('the registry proxy listens where its platform is told to send', () => {
/*
* The binary reads REGISTRY_PROXY_PORT rather than the platform's own PORT, so
* a revision told one port while the container listens on another never
* passes its first probe. The stack says the port out loud rather than
* trusting the binary's default to stay the provider's constant.
*/
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
assert.equal(read(seen.registryProxy.request.environment.REGISTRY_PROXY_PORT), '4100')
})
test('the registry proxy exports its telemetry to the collector', () => {
// The same trap the proxy's test above describes: both switches have no
// default in the binary, so leaving them unset ships a proxy that is healthy
// and silent.
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
const environment = seen.registryProxy.request.environment
assert.equal(read(environment.OTEL_LOGGING_ENABLED), 'true')
assert.equal(read(environment.OTEL_TRACING_ENABLED), 'true')
assert.equal(read(environment.OTEL_EXPORTER_OTLP_ENDPOINT), 'http://collector:4318')
assert.equal(read(environment.ENVIRONMENT), 'dev')
})
test('the registry proxy reads logins from the store the API writes them to', () => {
/*
* One decision reaching both: an API writing to one store and a proxy
* reading another is a stage where every private pull is anonymous and
* nothing reports why.
*/
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
assert.equal(seen.registryProxy.request.environment.REGISTRY_SECRET_STORE, 'gcp')
assert.equal(
seen.registryProxy.request.environment.REGISTRY_SECRET_STORE,
seen.api.request.environment.REGISTRY_SECRET_STORE,
)
assert.equal(seen.registryProxy.input.registryCredentials, seen.registryCredentials, 'and is handed the grant')
})
test('the registry proxy runs the image published for this commit', () => {
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
assert.equal(read(seen.registryProxy.request.image), `registry/${'a'.repeat(40)}-registry-proxy`)
})
test('the registry proxy takes its placement from the network, not a cluster host', () => {
// A managed service on the cloud that deploys it, like the runner a machine:
// neither is a task on the cluster, and a host handed to one would be a
// cluster task that nothing schedules.
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
assert.equal(seen.registryProxy.input.host, undefined)
assert.ok(seen.registryProxy.input.network, 'it is handed the network to take its own placement from')
})
test('a commit that published no registry proxy image fails before anything is built', () => {
const { providers } = bundle()
const withoutRegistryProxy = {
...providers,
images: (request: any) => ({
api: out(`registry/${request.tag}-api`),
proxy: out(`registry/${request.tag}-proxy`),
'otel-collector': out(`registry/${request.tag}-otel`),
}),
} as StackProviders
assert.throws(
() => deployStack({ providers: withoutRegistryProxy, config, inputs: inputs() }),
/mbuild published no registry-proxy image for this commit/,
)
})
test('the deploy reports the registry proxy where one runs, and nothing where none does', () => {
const active = bundle()
const outputs = deployStack({ providers: active.providers, config, inputs: inputs() })
assert.equal(read(outputs.registryProxyUrl), 'https://registry-proxy-123.run.app')
// The cloud that does not deploy one answers with the inactive handle, and
// the stack reports null for it rather than inventing an address.
const inactive = bundle()
const withoutRegistryProxy = {
...inactive.providers,
registryProxy: () => () => ({ active: false }),
} as unknown as StackProviders
const quiet = deployStack({ providers: withoutRegistryProxy, config, inputs: inputs() })
assert.equal(quiet.registryProxyUrl, null)
// And the rest of the stage deploys regardless: nothing on it calls a proxy
// that is not there.
assert.equal(read(quiet.apiUrl), 'https://dev.boxlite.ai')
})