Skip to content

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

17.9 KB
Raw Blame
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import * as pulumi from '@pulumi/pulumi'
import { mockRunnerStack } from './support/gcp-runner-stack.ts'

const isDeferred = (value: any): boolean =>
  Boolean(value) && (typeof value.then === 'function' || (typeof value.apply === 'function' && !('value' in value)))

const resolveOutput = async (value: any): Promise<any> => {
  if (value && typeof value.promise === 'function') return resolveOutput(await value.promise())
  if (value && typeof value.then === 'function') return resolveOutput(await value)
  if (value && typeof value.apply === 'function') {
    return 'value' in value
      ? resolveOutput(value.value)
      : new Promise((resolve, reject) => {
          try {
            value.apply((resolved: any) => {
              resolveOutput(resolved).then(resolve, reject)
            })
          } catch (error) {
            reject(error)
          }
        })
  }
  return value
}

const asyncOutput = (promise: Promise<any>): any => {
  promise.catch(() => {})
  return {
    promise: () => promise,
    apply: (fn: (value: any) => any) => asyncOutput(promise.then((resolved) => resolveOutput(fn(resolved)))),
  }
}

test('GCP rollout batches observe one host before updating the fleet', async (t) => {
  const { output, globals, resources, provider, requestFor, secretInputs } = mockRunnerStack(t)
  const servingFetch = (url: string, ids: string[] = ['12345']) => ({
    url: output(url),
    enrolledInstanceIds: output(ids),
  })
  await t.test('GCE identity lookup follows registration and feeds only OS Config with the verified fetch URL', async () => {
    for (const count of [1, 2]) {
      resources.clear()
      const request = requestFor(count)
      request.fleet = request.fleet.map((host, index) => ({ ...host, token: 'test-token-' + index }))
      const url = 'https://secret-fetch-123.us-east5.run.app'
      provider({
        ...request,
        deploySecretFetch(registry) {
          assert.equal(registry, resources.get('SecretServerRunnerRegistry')!.resource.stdout)
          return servingFetch(url)
        },
      })
      const lookup = resources.get('SecretServerRunnerRegistry')!
      assert.ok(secretInputs.has(lookup.args.stdin), 'Pulumi must encrypt the token-bearing command input')
      assert.equal(lookup.args.logging, 'none')
      assert.equal(lookup.args.addPreviousOutputInEnv, false)
      const { stdin, ...publicInputs } = lookup.args
      assert.ok(!JSON.stringify(publicInputs).includes('test-token'))
      assert.deepEqual(JSON.parse(stdin.value), [
        { name: 'default', token: 'test-token-0', vmName: 'boxlite-app-dev-runner' },
        ...(count === 2 ? [{ name: 'runner-2', token: 'test-token-1', vmName: 'boxlite-app-dev-runner-2' }] : []),
      ])
      for (const host of request.fleet) {
        const instance = resources.get(host.slot.resourceName)!
        assert.ok(lookup.options.dependsOn.includes(instance.resource))
        assert.doesNotMatch(instance.args.metadataStartupScript.value, /^SECRET_SERVER_URL=/m)
      }
      if (count === 2) assert.ok(lookup.options.dependsOn.includes(resources.get('RegisterExtraRunners')!.resource))
      const policy = resources.get('RunnerBinary')!.args.osPolicies.find((p: any) => p.id === 'runner-enrolled-binary')
      const steps = await resolveOutput(policy.resourceGroups[0].resources)
      assert.deepEqual(
        steps.map((step: any) => step.id),
        ['converge-unit-environment', 'swap-binary', 'configure-thp'],
      )
      assert.match(steps[1].exec.enforce.script, /Cannot confirm the running Runner version/)
      assert.equal(steps[0].exec.enforce.script.value.match(/'SECRET_SERVER_URL=([^']+)'/)?.[1], url)
    }
  })
  await t.test('THP step ordering gates KRUN_USE_THP=1 opt-in without blocking opt-out or upgrades', async () => {
    for (const deploySecretFetch of [false, true]) {
      for (const [runnerEnv, expected] of [
        ['{"KRUN_USE_THP":"1"}', deploySecretFetch ? ['configure-thp', 'converge-unit-environment', 'swap-binary'] : ['configure-thp', 'converge-unit-environment']],
        ['{}', deploySecretFetch ? ['converge-unit-environment', 'swap-binary', 'configure-thp'] : ['converge-unit-environment', 'configure-thp']],
        ['{"KRUN_USE_THP":"0"}', deploySecretFetch ? ['converge-unit-environment', 'swap-binary', 'configure-thp'] : ['converge-unit-environment', 'configure-thp']],
      ] as const) {
        resources.clear()
        const request = requestFor(1)
        request.environment = { BOXLITE_RUNNER_ENV: runnerEnv }
        if (deploySecretFetch) request.deploySecretFetch = () => servingFetch('https://fetch.example.test')
        provider(request)
        const policyId = deploySecretFetch ? 'runner-enrolled-binary' : 'runner-unit-env'
        const assignment = resources.get('RunnerBinary')
        assert.ok(assignment)
        const policy = assignment.args.osPolicies.find((p: any) => p.id === policyId)
        const steps = await resolveOutput(policy.resourceGroups[0].resources)
        assert.deepEqual(
          steps.map((step: any) => step.id),
          expected,
        )
      }
    }
  })
  await t.test('THP step ordering resolves deferred BOXLITE_RUNNER_ENV Inputs (Output and Promise)', async (t) => {
    const previousResolve = Object.getOwnPropertyDescriptor(globalThis, '$resolve')
    Object.defineProperty(globalThis, '$resolve', {
      configurable: true,
      value: (values: any[]) =>
        values.some(isDeferred)
          ? asyncOutput(Promise.all(values.map(resolveOutput)))
          : previousResolve!.value(values),
    })
    t.after(() => {
      if (previousResolve) Object.defineProperty(globalThis, '$resolve', previousResolve)
      else Reflect.deleteProperty(globalThis, '$resolve')
    })

    for (const [kind, wrap] of [
      ['string', (value: string) => value],
      ['pulumi.output', (value: string) => pulumi.output(value) as unknown as $util.Input<string>],
      ['Promise', (value: string) => Promise.resolve(value)],
    ] as const) {
      for (const deploySecretFetch of [false, true]) {
        for (const [runnerEnv, expected] of [
          [
            '{"KRUN_USE_THP":"1"}',
            deploySecretFetch
              ? ['configure-thp', 'converge-unit-environment', 'swap-binary']
              : ['configure-thp', 'converge-unit-environment'],
          ],
          [
            '{"KRUN_USE_THP":"0"}',
            deploySecretFetch
              ? ['converge-unit-environment', 'swap-binary', 'configure-thp']
              : ['converge-unit-environment', 'configure-thp'],
          ],
        ] as const) {
          resources.clear()
          const request = requestFor(1)
          request.environment = { BOXLITE_RUNNER_ENV: wrap(runnerEnv) }
          if (deploySecretFetch) request.deploySecretFetch = () => servingFetch('https://fetch.example.test')
          provider(request)
          const policyId = deploySecretFetch ? 'runner-enrolled-binary' : 'runner-unit-env'
          const assignment = resources.get('RunnerBinary')
          assert.ok(assignment, `${kind} failed to create RunnerBinary`)
          const policy = assignment.args.osPolicies.find((p: any) => p.id === policyId)
          const steps = await resolveOutput(policy.resourceGroups[0].resources)
          assert.deepEqual(
            steps.map((step: any) => step.id),
            expected,
          )
        }
      }
      for (const invalidEnv of ['{', 'null', '[]', '{"KRUN_USE_THP":1}']) {
        resources.clear()
        await assert.rejects(async () => {
          const request = requestFor(1)
          request.environment = { BOXLITE_RUNNER_ENV: wrap(invalidEnv) }
          provider(request)
          const assignment = resources.get('RunnerBinary')
          assert.ok(assignment, `${kind} invalid env failed before creating RunnerBinary`)
          const policy = assignment.args.osPolicies.find((p: any) => p.id === 'runner-unit-env')
          await resolveOutput(policy.resourceGroups[0].resources)
        }, /BOXLITE_RUNNER_ENV/)
      }
    }
  })
  await t.test('a new VM can start serving jobs only after its live identity and fetch URL converge', async (t) => {
    resources.clear()
    const url = 'https://fetch.example.test'
    provider({ ...requestFor(1), deploySecretFetch: () => servingFetch(url, ['44556']) })
    const boot: string = resources.get('Runner')!.args.metadataStartupScript.value
    const start = /^ExecStart=(.+)$/m.exec(boot)![1]!
    const wrapper =
      start === '/usr/local/bin/boxlite-runner'
        ? 'exec /usr/local/bin/boxlite-runner'
        : boot.split("<< 'STARTWRAP'\n")[1]!.split('\nSTARTWRAP\n')[0]!
    const dir = mkdtempSync(join(tmpdir(), 'runner-admission-'))
    t.after(() => rmSync(dir, { recursive: true, force: true }))
    const envFile = join(dir, 'runner.env')
    writeFileSync(envFile, boot.split("<< 'RUNNERENV'\n")[1]!.split('\nRUNNERENV\n')[0]! + '\n')
    writeFileSync(join(dir, 'runner'), '#!/bin/sh\nprintf "%s" "$SECRET_SERVER_URL" > "$SERVED"\n', { mode: 0o700 })
    writeFileSync(join(dir, 'start'), wrapper.replace('exec /usr/local/bin/boxlite-runner', 'exec runner'))
    writeFileSync(join(dir, 'curl'), '#!/bin/sh\nprintf "%s" "$VM_ID"\n', { mode: 0o700 })
    const unitDir = join(dir, 'boxlite-runner.service.d')
    const launch = `set -a; . ./runner.env
for dropin in "$BOXLITE_RUNNER_UNIT_DIR"/*.conf; do
  if [[ -f "$dropin" ]]; then . "$(sed -n 's/^EnvironmentFile=//p' "$dropin")"; fi
done
exec bash ./start`
    writeFileSync(join(dir, 'systemctl'), `#!/usr/bin/env bash\nif [ "$1" = restart ]; then ${launch}; fi\n`, {
      mode: 0o700,
    })
    const served = join(dir, 'served')
    const execute = (script: string, id: string) =>
      spawnSync('bash', ['-c', script], {
        cwd: dir,
        encoding: 'utf8',
        env: {
          PATH: dir + ':' + process.env.PATH,
          VM_ID: id,
          BOXLITE_RUNNER_HOST_NAME: 'boxlite-app-dev-runner',
          BOXLITE_RUNNER_ENV_FILE: envFile,
          BOXLITE_RUNNER_UNIT_DIR: unitDir,
          SERVED: served,
        },
      })
    assert.notEqual(execute(launch, '44556').status, 0, 'unenrolled Runner started at boot')
    const policy = resources.get('RunnerBinary')!.args.osPolicies.find((p: any) => p.id === 'runner-enrolled-binary')
    const { validate, enforce } = (await resolveOutput(policy.resourceGroups[0].resources))[0].exec
    assert.notEqual(execute(enforce.script.value, '12345').status, 100, 'old registry admitted a replacement VM')
    assert.equal(existsSync(served), false)
    const activated = execute(enforce.script.value, '44556')
    assert.equal(activated.status, 100, activated.stderr)
    assert.equal(readFileSync(served, 'utf8'), url)
    assert.equal(execute(validate.script.value, '44556').status, 100)
    const bootEnv = boot.split("<< 'RUNNERENV'\n")[1]!.split('\nRUNNERENV\n')[0]! + '\n'
    writeFileSync(envFile, bootEnv)
    assert.equal(execute(launch, '44556').status, 0, 'reboot erased enrollment')
    assert.notEqual(execute(launch, '12345').status, 0, 'stale enrollment accepted another VM')
  })
  await t.test('enrollment is delivered even when OS Config runs before bootstrap', async (t) => {
    resources.clear()
    provider({ ...requestFor(1), deploySecretFetch: () => servingFetch('https://fetch.example.test') })
    const resolvedPolicies = await Promise.all(
      resources.get('RunnerBinary')!.args.osPolicies.map(async (p: any) => ({
        ...p,
        resolvedResources: await Promise.all(
          p.resourceGroups.map(async (group: any) => await resolveOutput(group.resources)),
        ),
      })),
    )
    const policy = resolvedPolicies.find((p: any) =>
      p.resolvedResources[0].some((r: any) => r.id === 'converge-unit-environment'),
    )
    const scripts = policy.resolvedResources[0].find((r: any) => r.id === 'converge-unit-environment').exec
    const dir = mkdtempSync(join(tmpdir(), 'early-runner-'))
    t.after(() => rmSync(dir, { recursive: true, force: true }))
    writeFileSync(join(dir, 'curl'), '#!/bin/sh\necho 12345\n', { mode: 0o700 })
    writeFileSync(join(dir, 'systemctl'), '#!/bin/sh\n[ "$1" = daemon-reload ]\n', { mode: 0o700 })
    const exec = (script: string) =>
      spawnSync('bash', ['-c', script], {
        encoding: 'utf8',
        env: {
          PATH: dir + ':' + process.env.PATH,
          BOXLITE_RUNNER_ENV_FILE: join(dir, 'etc', 'runner.env'),
          BOXLITE_RUNNER_HOST_NAME: 'boxlite-app-dev-runner',
          BOXLITE_RUNNER_UNIT_DIR: join(dir, 'unit.d'),
        },
      })
    assert.equal(exec(scripts.validate.script.value).status, 101, 'fresh VM reported compliant before enrollment')
    const result = exec(scripts.enforce.script.value)
    assert.equal(result.status, 100, result.stderr)
    assert.equal(exec(scripts.validate.script.value).status, 100)
    assert.equal(existsSync(join(dir, 'etc', 'runner.env')), false)
    const file = readFileSync(join(dir, 'unit.d', '50-secret-fetch.conf'), 'utf8').match(/^EnvironmentFile=(.+)$/m)![1]!
    assert.match(readFileSync(file, 'utf8'), /^BOXLITE_SECRET_FETCH_INSTANCE_ID=12345$/m)
  })
  await t.test('an old updater cannot overwrite the enrolled Runner policy', () => {
    resources.clear()
    provider({ ...requestFor(1), deploySecretFetch: () => servingFetch('https://fetch.example.test') })
    const policies = resources.get('RunnerBinary')!.args.osPolicies
    assert.equal(
      policies.some((p: any) => p.id === 'runner-binary'),
      false,
      'legacy runner:update accepts the assignment and overwrites enrollment',
    )
  })
  await t.test('GCP observes the first runner then updates every other runner in parallel', () => {
    for (const count of [4, 1, 12]) {
      resources.clear()
      provider(requestFor(count))
      const canary = resources.get('RunnerBinary')!
      assert.deepEqual(canary.options.customTimeouts, { create: '40m', update: '40m' })
      assert.deepEqual(canary.args.instanceFilter.inclusionLabels, [
        { labels: { 'boxlite-runner': 'default', 'boxlite-stage': 'dev' } },
      ])
      assert.equal(canary.args.name, 'boxlite-app-dev-runner-binary')
      const binaryPolicy = canary.args.osPolicies.find((policy: any) => policy.id === 'runner-binary')
      assert.deepEqual(binaryPolicy.resourceGroups[0].resources.map((resource: any) => resource.id), ['swap-binary'])
      assert.ok(canary.args.osPolicies.some((policy: any) => policy.id === 'runner-unit-env'))
      assert.ok(
        canary.args.osPolicies.some((policy: any) =>
          policy.resourceGroups.some((group: any) =>
            group.resources.some((resource: any) => resource.pkg?.apt?.name === 'nfs-common'),
          ),
        ),
        'existing hosts need the NFS client even when the runner binary is current',
      )
      assert.deepEqual(canary.args.rollout, { disruptionBudget: { fixed: 1 }, minWaitDuration: '300s' })
      assert.equal(canary.args.skipAwaitRollout, false)
      const fleet = resources.get('RunnerBinaryFleet')
      if (count === 1) {
        assert.equal(fleet, undefined)
        continue
      }
      assert.ok(fleet)
      assert.deepEqual(fleet.options.customTimeouts, { create: '40m', update: '40m' })
      assert.equal(fleet.args.name, 'boxlite-app-dev-runner-binary-fleet')
      assert.deepEqual(
        fleet.args.instanceFilter.inclusionLabels,
        Array.from({ length: count - 1 }, (_, index) => ({
          labels: { 'boxlite-runner': `runner-${index + 2}`, 'boxlite-stage': 'dev' },
        })),
      )
      assert.deepEqual(fleet.args.rollout, { disruptionBudget: { percent: 100 }, minWaitDuration: '0s' })
      assert.equal(fleet.args.skipAwaitRollout, false)
      assert.ok(fleet.options.dependsOn.includes(canary.resource))
      assert.deepEqual(fleet.args.osPolicies, canary.args.osPolicies)
    }
  })
  await t.test('GCP policies select only their own stage in a shared project', () => {
    const matches = (policy: any, labels: Record<string, string>) =>
      policy.instanceFilter.inclusionLabels.some(({ labels: required }: any) =>
        Object.entries(required).every(([key, value]) => labels[key] === value),
      )
    for (const count of [1, 2]) {
      const stages = new Map<string, { hosts: any[]; policies: any[] }>()
      for (const stage of ['dev', 'stage']) {
        globals.$app.stage = stage
        resources.clear()
        const request = requestFor(count)
        for (const host of request.fleet) host.slot.nameTag = host.slot.nameTag.replace('-dev-', '-' + stage + '-')
        provider(request)
        stages.set(stage, {
          hosts: [...resources.entries()]
            .filter(([name]) => /^Runner(?:-runner-\d+)?$/.test(name))
            .map(([, entry]) => entry.args),
          policies: ['RunnerBinary', 'RunnerBinaryFleet'].flatMap((name) =>
            resources.has(name) ? [resources.get(name)!.args] : [],
          ),
        })
      }
      for (const [stage, { hosts, policies }] of stages) {
        const others = stages.get(stage === 'dev' ? 'stage' : 'dev')!.hosts
        assert.equal(hosts.length, count)
        assert.equal(policies.length, count)
        for (const policy of policies) {
          assert.ok(
            hosts.some((host) => matches(policy, host.labels)),
            'each batch selects an own-stage host',
          )
          assert.ok(
            others.every((host) => !matches(policy, host.labels)),
            stage + ' policy selected another stage',
          )
          for (const host of hosts) {
            const { 'boxlite-stage': _stage, ...legacy } = host.labels
            assert.equal(matches(policy, legacy), false, 'unscoped hosts must not match')
          }
        }
      }
    }
    globals.$app.stage = 'dev'
  })
  await t.test('GCP refuses normalized labels that would overlap the two batches', () => {
    const request = requestFor(4)
    request.fleet[0]!.slot.controlPlaneRunnerName = 'RUNNER.2'
    resources.clear()
    assert.throws(() => provider(request), /runner labels.*unique/)
    assert.equal(resources.size, 0)
  })
})