Skip to content

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

8.0 KB
Raw Blame
import assert from 'node:assert/strict'
import test from 'node:test'
import { apiEnvironmentFrom } from '../src/api-environment.ts'
import { gcpApiProvider } from '../stack/providers/gcp/api.ts'
import * as gcpSdk from '@pulumi/gcp'
import { componentTargets } from '../src/components.ts'

class Value {
  constructor(readonly __output: any) {}
  apply(fn: (value: any) => any): Value {
    return value(fn(this.__output))
  }
}
const value = (input: any): Value => (input instanceof Value ? input : new Value(input))
const unwrap = (input: any): any =>
  input instanceof Value
    ? unwrap(input.__output)
    : Array.isArray(input)
      ? input.map(unwrap)
      : input && typeof input === 'object'
        ? Object.fromEntries(Object.entries(input).map(([key, item]) => [key, unwrap(item)]))
        : input

function capture(configured: boolean, minInstances?: number, instance?: { cpu: number; memoryMiB: number }, maxInstances?: number) {
  const records: { type: string; name: string; args: any }[] = []
  const namespace = (path: string): any =>
    new Proxy(function () {}, {
      get: (_target, key) => namespace(path + '.' + String(key)),
      apply: () => {
        if (path === 'gcp.organizations.getProjectOutput') return { number: value('123456789012') }
        throw new Error(`Unexpected provider lookup: ${path}`)
      },
      construct: (_target, [name, args]) => {
        records.push({ type: path, name, args })
        return new Proxy(
          {},
          {
            get: (_object, key) =>
              key === 'dnsResourceRecords'
                ? [{ name: '_authorization.example.test', type: 'CNAME', data: 'example.test' }]
                : value(
                    key === 'name'
                      ? (args.name ?? name)
                      : key === 'address'
                        ? '192.0.2.1'
                        : `resource-${name}-${String(key)}`,
                  ),
          },
        )
      },
    })
  Object.assign(globalThis, {
    $app: { name: 'boxlite', stage: 'ci-test' },
    $util: { output: value, secret: value },
    $resolve: (items: any[]) => value(items.map(unwrap)),
    gcp: namespace('gcp'),
    cloudflare: namespace('cloudflare'),
  })
  const secrets = ['CI_GITHUB_APP_PRIVATE_KEY', 'CI_GITHUB_WEBHOOK_SECRET', 'CI_SECRET_ENCRYPTION_KEY']
  const ci = configured
    ? {
        CI_GITHUB_APP_CLIENT_ID: 'test-client',
        CI_GITHUB_APP_SLUG: 'test-app',
        ...Object.fromEntries(
          secrets.map((key, i) => [
            key,
            JSON.stringify({ address: `projects/test-project/secrets/ci-${i}/versions/7` }),
          ]),
        ),
      }
    : {}
  const channels = apiEnvironmentFrom({
    environment: {
      STACK_DOMAIN: 'example.test',
      OIDC_ISSUER_BASE_URL: 'https://auth.example.test',
      ...ci,
    },
    declaration: {
      groups: { deploy: [], api: Object.keys(ci), secret: configured ? secrets : [] },
      where: '/test/mstage.config.json',
    },
    region: 'us-east5',
    stage: 'ci-test',
    home: 'gcp',
  })
  gcpApiProvider({
    zone: 'us-east1-c',
    dependencies: {
      placement: {
        cloud: 'gcp',
        serviceAccount: value('[email protected]'),
        subnetwork: value('subnet'),
        egressSubnetwork: value('subnet'),
      },
      storage: {
        name: value('bucket'),
        binding: {
          cloud: 'gcp',
          credentialVending: {
            serviceAccount: value('[email protected]'),
          },
          volumeCondition: { expression: 'true' },
        },
      },
      database: {
        binding: {
          cloud: 'gcp',
          passwordRef: value('projects/test-project/secrets/db/versions/1'),
          connectionName: value('test-project:us-east5:db'),
        },
      },
      cache: {
        binding: {
          cloud: 'gcp',
          passwordRef: value('projects/test-project/secrets/cache/versions/1'),
          caRef: value('projects/test-project/secrets/cache-ca/versions/1'),
        },
      },
      clickhouse: { active: false },
      waitFor: [],
    } as any,
    project: 'test-project',
    region: 'us-east5',
    domain: 'example.test',
    dashboardDomain: null,
    callers: [],
    zoneId: 'zone',
    network: value('network') as any,
    runnerAccount: value('[email protected]') as any,
  })({ ...channels, minInstances, maxInstances, instance, image: 'registry.example.test/api:fixture', port: 3000, capabilities: [] } as any)
  const service = records.find((r) => r.type === 'gcp.cloudrunv2.Service' && r.name === 'Api')
  assert.ok(service)
  return { service: unwrap(service.args), records }
}

test('the Cloud Run API retains background CPU and uses the hosted CI default when the minimum is omitted', () => {
  const on = capture(true).service
  assert.deepEqual(on.scaling, { minInstanceCount: 1 })
  assert.equal(on.template.containers[0].resources.cpuIdle, false)
  assert.equal(on.ingress, 'INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER')
  const off = capture(false).service
  assert.equal(off.scaling, undefined)
  assert.equal(off.template.containers[0].resources.cpuIdle, false)
})

test('the configured service minimum overrides the hosted CI default', () => {
  assert.deepEqual(capture(true, 0).service.scaling, { minInstanceCount: 0 })
  assert.deepEqual(capture(true, 5).service.scaling, { minInstanceCount: 5 })
  assert.deepEqual(capture(false, 5).service.scaling, { minInstanceCount: 5 })
  const { service } = capture(true, undefined, undefined, 15)
  assert.deepEqual(service.scaling, { minInstanceCount: 1, maxInstanceCount: 15 })
  assert.deepEqual(service.template.scaling, { maxInstanceCount: 15 })
})

test('Cloud Run receives instance limits only when a stage specifies them', () => {
  assert.deepEqual(capture(false).service.template.containers[0].resources, { cpuIdle: false })
  const { service } = capture(false, 5, { cpu: 2, memoryMiB: 2048 })
  assert.deepEqual(service.template.containers[0].resources, { cpuIdle: false, limits: { cpu: '2', memory: '2048Mi' } })
  assert.deepEqual(service.scaling, { minInstanceCount: 5 })
})

test('API targeting includes newly configured secret grants absent from the previous state', () => {
  const { records } = capture(true)
  const services = records.filter(
    (record) => record.type === 'gcp.cloudrunv2.Service' && ['Api', 'CloudAppWorker'].includes(record.name),
  )
  assert.deepEqual(services.map((service) => service.name).sort(), ['Api', 'CloudAppWorker'])
  const prefix = 'urn:pulumi:ci-test::boxlite::'
  const apiType = (gcpSdk.cloudrunv2.Service as any).__pulumiType
  const targets = componentTargets({
    components: 'api',
    app: 'boxlite',
    stage: 'ci-test',
    environment: {},
    resources: services.map((service) => ({ type: apiType, urn: `${prefix}${apiType}::${service.name}` })),
  })
  const grants = records.filter((record) => record.type === 'gcp.secretmanager.SecretIamMember')
  const grantType = (gcpSdk.secretmanager.SecretIamMember as any).__pulumiType
  assert.ok(grants.some((grant) => grant.name === 'ApiSecretAccess-CI_GITHUB_APP_PRIVATE_KEY'))
  const secretTarget = targets.find((target) => target.endsWith('::ApiSecretAccess-*'))
  assert.ok(secretTarget)
  for (const grant of grants) {
    const urn = `${prefix}${grantType}::${grant.name}`
    assert.ok(urn.startsWith(secretTarget.slice(0, -1)), `${grant.name} is outside the target scope`)
  }
})

test('CI refs reach actual Cloud Run envs and per-secret grants, without plaintext payloads', () => {
  const { service, records } = capture(true)
  for (const [i, name] of [
    'CI_GITHUB_APP_PRIVATE_KEY',
    'CI_GITHUB_WEBHOOK_SECRET',
    'CI_SECRET_ENCRYPTION_KEY',
  ].entries()) {
    const variable = service.template.containers[0].envs.find((e: any) => e.name === name)
    assert.deepEqual(variable, { name, valueSource: { secretKeyRef: { secret: `ci-${i}`, version: '7' } } })
    const grant = records.find((r) => r.name === 'ApiSecretAccess-' + name)
    assert.ok(grant)
    assert.equal(unwrap(grant.args.secretId), `ci-${i}`)
    assert.equal(grant.args.role, 'roles/secretmanager.secretAccessor')
  }
})