Skip to content

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

6.2 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 BoxLite AI
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { delimiter, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import test from 'node:test'
import { data, Evaluator, Lexer, Parser } from '@actions/expressions'
import { load } from 'js-yaml'
import { cacheKey } from '../../../.github/actions/release-build-cache/record.mjs'
import { buildKey } from './release-build-plan.mjs'

const root = fileURLToPath(new URL('../../../', import.meta.url))
const jobs = load(readFileSync(join(root, '.github/workflows/mbuild-release.yml'), 'utf8')).jobs
const cache = load(readFileSync(join(root, '.github/actions/release-build-cache/action.yml'), 'utf8'))
const hash = bytes => createHash('sha256').update(bytes).digest('hex')
const tag = 'v1.2.3'
const sha = '1'.repeat(40)
const manifest = 'sha256:' + hash('manifest')
const blob = 'sha256:' + hash('runner bytes')

function evaluate(expression, context) {
  const raw = expression.replace(/^\$\{\{\s*|\s*\}\}$/g, '')
  const ast = new Parser(new Lexer(raw).lex().tokens, Object.keys(context), []).parse()
  return new Evaluator(ast, JSON.parse(JSON.stringify(context), data.reviver)).evaluate().coerceString()
}

function fixture(t) {
  const dir = mkdtempSync(join(tmpdir(), 'boxlite-publisher-'))
  t.after(() => rmSync(dir, { recursive: true, force: true }))
  const env = { ...process.env, PATH: dir + delimiter + process.env.PATH, GITHUB_REPOSITORY: 'boxlite-ai/boxlite',
    GITHUB_OUTPUT: join(dir, 'outputs'), RUNNER_TEMP: dir, GITHUB_ACTOR: 'fixture', GH_TOKEN: 'fixture',
    GITHUB_RUN_ATTEMPT: '2', GITHUB_RUN_ID: '10', TAG: tag, SHA: sha, REGISTRY_CONFIG: join(dir, 'auth.json'),
    DENY_LOGIN: '0', DENY_MANIFEST: '0', DENY_BLOB: '0', BLOB_BYTES: 'runner bytes', REMOTE: manifest, BLOB: blob }
  writeFileSync(env.GITHUB_OUTPUT, '')
  writeFileSync(join(dir, 'oras'), `#!/bin/sh
set -eu
case "$1" in
  login) cat >/dev/null; exit "$DENY_LOGIN" ;;
  resolve) printf '%s\\n' "$REMOTE" ;;
  manifest|blob)
    test "$2" = fetch
    case "$*" in *anonymous*) ;; *) exit 4 ;; esac
    jq -e '. == {"auths":{}}' "$RUNNER_TEMP/anonymous-registry.json" >/dev/null
    if [ "$1" = manifest ]; then
      test "$DENY_MANIFEST" = 0
      printf '{"layers":[{"digest":"%s"}]}\\n' "$BLOB"
    else
      test "$DENY_BLOB" = 0
      case "$*" in *'--output -'*) printf '%s' "$BLOB_BYTES" ;; *) exit 5 ;; esac
    fi ;;
  *) exit 6 ;;
esac
`, { mode: 0o755 })
  return { dir, env }
}

test('resolve still plans a full retry when registry login is unavailable', t => {
  const { dir, env } = fixture(t)
  const wheel = JSON.stringify({ scope: buildKey(tag, sha, 10), unit: 'wheels-darwin-arm64', attempt: 1, check: '321', receipt: hash('wheel'), manifest: '' })
  const producer = { name: 'build wheels on macOS', conclusion: 'success', run_attempt: 1,
    check_run_url: 'checks/321', steps: [{ name: 'Build cache receipt ' + wheel, conclusion: 'success' }] }
  writeFileSync(join(dir, 'jobs.json'), JSON.stringify([{ jobs: [producer] }]))
  writeFileSync(join(dir, 'gh'), '#!/bin/sh\ncat "$RUNNER_TEMP/jobs.json"\n', { mode: 0o755 })
  const step = jobs.resolve.steps.find(step => step.id === 'retry')
  const result = spawnSync('bash', ['-c', step.run], { cwd: root, env: { ...env, DENY_LOGIN: '1' }, encoding: 'utf8' })
  assert.equal(result.status, 0, result.stderr)
  assert.equal(JSON.parse(readFileSync(env.GITHUB_OUTPUT, 'utf8').trim().slice(5)).sources['wheels-darwin-arm64'].key, cacheKey(wheel))
  assert.ok(!jobs.resolve.steps.some(step => step.uses?.startsWith('oras-project/')))
})

test('a tag changed after resolve turns a verified local cache hit into a publisher miss', t => {
  const { dir, env } = fixture(t)
  const check = cache.runs.steps.find(step => step.id === 'registry')
  for (const remote of [manifest, 'sha256:' + hash('replacement')]) {
    const outputs = {}
    if (check) {
      writeFileSync(env.GITHUB_OUTPUT, '')
      const result = spawnSync('bash', ['-c', check.run], { cwd: dir, env: { ...env, REMOTE: remote, MANIFEST: manifest.slice(7),
        REGISTRY_REF: 'ghcr.io/boxlite-ai/boxlite/runner:' + tag + '-' + sha }, encoding: 'utf8' })
      assert.equal(result.status, 0, result.stderr)
      for (const line of readFileSync(env.GITHUB_OUTPUT, 'utf8').trim().split('\n')) {
        const [key, value] = line.split('=')
        outputs[key] = value
      }
    }
    const context = { inputs: { 'registry-ref': 'ghcr.io/boxlite-ai/boxlite/runner:' + tag + '-' + sha },
      steps: { verify: { outputs: { hit: 'true' } }, registry: { outputs } } }
    assert.equal(evaluate(cache.outputs.hit.value, context), String(remote === manifest))
  }
  for (const job of [jobs.publish, jobs['publish-runner']]) {
    assert.ok(job.concurrency.group)
    assert.ok(job.steps.find(step => step.id === 'cache').with['registry-ref'])
    assert.match(job.steps.find(step => step.id === 'built').if, /steps.cache.outputs.hit != 'true'/)
  }
})

test('a cached Runner must be anonymously downloadable before pins are uploaded', t => {
  const { dir, env } = fixture(t)
  const job = jobs['publish-runner']
  const upload = job.steps.findIndex(step => step.with?.name === 'ghcr-runner')
  const step = job.steps.slice(0, upload).find(step => step.run?.includes('anonymous-registry.json'))
  const hit = { steps: { cache: { outputs: { hit: 'true' } } } }
  assert.ok(step && (!step.if || evaluate(step.if, hit) === 'true'), 'a cache hit skips anonymous verification')
  writeFileSync(join(dir, 'runner.json'), JSON.stringify({ manifest, archive: blob }))
  writeFileSync(join(dir, 'boxlite-runner-' + tag + '-linux-amd64.tar.gz'), 'runner bytes')
  for (const [overrides, success] of [[{}, true], [{ BLOB: 'sha256:' + hash('wrong layer') }, false], [{ DENY_MANIFEST: '1' }, false], [{ DENY_BLOB: '1' }, false],
    [{ BLOB_BYTES: 'wrong bytes' }, false], [{ REMOTE: 'sha256:' + hash('replacement') }, false]]) {
    const result = spawnSync('bash', ['-c', step.run], { cwd: dir, env: { ...env, ...overrides }, encoding: 'utf8' })
    assert.equal(result.status === 0, success, JSON.stringify(overrides) + ' ' + result.stderr)
  }
})