The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
import assert from 'node:assert/strict'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
import * as pulumi from '@pulumi/pulumi'
import * as gcp from '@pulumi/gcp'
import * as random from '@pulumi/random'
import { installGlobals } from '../pulumi/program.ts'
import type { Network } from '../stack/network.ts'
import { gcpStackProviders } from '../stack/providers/gcp/index.ts'
import { secretServerAlarms } from '../stack/providers/gcp/alarms.ts'
import { secretServerEndpoint } from '../stack/providers/gcp/secret-server.ts'
test('deployment refuses to publish an audience missing from the serving URLs', () => {
const write = 'https://write.run.app'
const fetch = 'https://fetch.run.app'
assert.equal(secretServerEndpoint(fetch, fetch, []), fetch)
assert.equal(secretServerEndpoint(fetch, write, [write, fetch]), fetch)
assert.throws(() => secretServerEndpoint(fetch, write, [write]), /did not publish/)
assert.throws(() => secretServerEndpoint(fetch, write, []), /did not publish/)
})
test('rejects invalid alert budgets and notification channels outside the stage', () => {
const args = { project: 'boxlite-test', channel, api: 'api', fetch: pulumi.output('fetch') as unknown as $util.Output<string> }
for (const limit of ['0', '1.5', 'Infinity', '9007199254740992']) {
assert.throws(() => secretServerAlarms({ ...args, limit }), /SECRET_SERVER_FETCH_LIMIT/)
}
assert.throws(
() => secretServerAlarms({ ...args, channel: 'projects/other/notificationChannels/1' }),
/SECRET_SERVER_INCIDENT_CHANNEL/,
)
})
const project = 'boxlite-test'
const region = 'us-east5'
const privateSubnetId = `projects/${project}/regions/${region}/subnetworks/private`
const channel = `projects/${project}/notificationChannels/123`
const connectionName = `${project}:${region}:existing-instance`
const runnerRegistry = '{"gcp_iit":{"12345":"11111111-1111-4111-8111-111111111111"}}'
const alarms = ['SecretServerDecryptFailure', 'SecretServerReplay', 'SecretServerRunnerVolume']
async function provision(stage: string, configuredChannel?: string, servingRegistry = runnerRegistry) {
process.env.MSTAGE_CONFIG ??= fileURLToPath(new URL('../../.mstage.config.example.json', import.meta.url))
const inputs = new Map<string, Record<string, any>>()
const channelLookups: unknown[] = []
await pulumi.runtime.setMocks(
{
newResource(args) {
inputs.set(args.name, args.inputs)
const state = { ...args.inputs }
let id = args.name
if (args.type === 'gcp:secretmanager/secret:Secret') id = `projects/${project}/secrets/${state.secretId}`
if (args.type === 'gcp:secretmanager/secretVersion:SecretVersion') state.name = `${state.secret}/versions/7`
if (args.name === 'DatabasePassword') state.result = 'test/password'
if (args.name === 'SecretServerMasterKey') state.base64 = Buffer.alloc(32, 1).toString('base64')
if (args.name === 'Database') state.connectionName = connectionName
if (args.name === 'SecretServerAccount') state.email = '[email protected]'
if (args.type === 'gcp:cloudrunv2/service:Service') {
const deterministic = `https://${state.name}-12345.${region}.run.app`
const alias = `https://${state.name}-example.a.run.app`
state.uri = args.name === 'SecretServerFetch' ? alias : deterministic
state.urls = [alias, deterministic]
state.latestReadyRevision = state.latestCreatedRevision = state.name + '-0001'
state.generation = state.observedGeneration = '1'
state.reconciling = false
state.trafficStatuses = [{ revision: state.latestReadyRevision, percent: 100 }]
if (args.name === 'SecretServerFetch') {
state.template = structuredClone(state.template)
state.template.containers[0].envs.find((env: any) => env.name === 'SECRET_SERVER_RUNNER_REGISTRY').value =
servingRegistry
}
}
return { id, state }
},
call: ({ token, inputs: args }) => {
if (token.includes('getNotificationChannel')) {
channelLookups.push(args.displayName)
return { name: channel, enabled: true }
}
assert.match(token, /getProject/)
return { number: '12345' }
},
},
'boxlite',
stage,
)
installGlobals({
app: 'boxlite',
stage,
modules: { pulumi, gcp, random, cloudflare: {}, command: {}, kubernetes: {} },
})
const apiAccount = $util.output('[email protected]')
const runnerAccount = $util.output('[email protected]')
const binding = {
cloud: 'gcp' as const,
network: $util.output('vpc'),
subnetwork: $util.output(`https://www.googleapis.com/compute/v1/${privateSubnetId}`),
privateServiceAccess: $util.output('peering'),
cidr: $util.output('10.0.0.0/20'),
}
const endpoints = await pulumi.runtime.runInPulumiStack(async () => {
const network: Network = {
binding,
ready: [],
placementFor: (role) => ({
cloud: 'gcp',
exposure: 'private',
subnetwork: $util.output(privateSubnetId),
egressSubnetwork: $util.output(`projects/${project}/regions/${region}/subnetworks/cloudrun-egress`),
serviceAccount: role === 'api' ? apiAccount : runnerAccount,
}),
}
const providers = gcpStackProviders({
project,
region,
stage,
appShort: 'bl',
domain: 'example.test',
zoneId: 'zone',
artifactsBucket: 'artifacts',
volumePrefix: 'volumes',
secretServer: { channel: configuredChannel },
})
assert.ok(providers.secretServer)
const database = providers.database({ network })({
name: 'boxlite',
size: 'small',
highlyAvailable: false,
backupRetentionDays: 1,
protected: true,
})
const services = providers.secretServer({ network, database, image: 'candidate' })
const fetch = services.deployFetch($util.output(runnerRegistry))
return { writeUrl: services.writeUrl, fetchUrl: fetch.url, enrolledIds: fetch.enrolledInstanceIds }
})
await pulumi.runtime.disconnect()
return { inputs, endpoints, channelLookups }
}
test('both Secret Server Cloud Run roles attach to the private subnet by resource ID', async () => {
const { inputs } = await provision('dev')
const interfaces = ['SecretServerWrite', 'SecretServerFetch'].map(
(name) => inputs.get(name)!.template.vpcAccess.networkInterfaces,
)
assert.deepEqual(interfaces, [[{ subnetwork: privateSubnetId }], [{ subnetwork: privateSubnetId }]])
})
for (const stage of ['dev', 'stage', 'prod']) {
test(`${stage} labels both Secret Server roles, keeps each service warm and bounds revision scaling`, async () => {
const { inputs } = await provision(stage)
for (const name of ['SecretServerWrite', 'SecretServerFetch']) {
const service = inputs.get(name)!
assert.equal(service.labels?.stage, stage, name)
assert.equal(service.scaling?.minInstanceCount, 1, name)
assert.equal(service.template.scaling.maxInstanceCount, 2, name)
}
})
test(`${stage} without a channel deploys both Secret Server roles and skips alarm resources and channel lookup`, async () => {
const { inputs, endpoints, channelLookups } = await provision(stage)
assert.ok(endpoints?.writeUrl && endpoints.fetchUrl)
assert.deepEqual(channelLookups, [])
for (const name of alarms) {
assert.equal(inputs.has(name), false, name)
assert.equal(inputs.has(name + 'Metric'), false, name + 'Metric')
}
})
test(`${stage} with an explicit channel sends every Secret Server alert to it`, async () => {
const { inputs, channelLookups } = await provision(stage, channel)
assert.deepEqual(channelLookups, [])
for (const name of alarms) assert.deepEqual(inputs.get(name)!.notificationChannels, [channel])
})
}
test('both production Cloud Run roles start on the separate SQL database with pinned secrets and distinct invokers', async () => {
const { inputs, endpoints, channelLookups } = await provision('prod', channel)
assert.deepEqual(channelLookups, [])
assert.equal(inputs.get('SecretServerDatabase')!.instance, inputs.get('DatabaseSchema')!.instance)
const urlValue = inputs.get('SecretServerDatabaseUrlValue')!.secretData
const url = new URL(typeof urlValue === 'string' ? urlValue : urlValue.value)
assert.equal(url.searchParams.get('user'), inputs.get('DatabaseUser')!.name)
assert.equal(url.pathname, '/boxlite_secrets')
assert.equal(url.searchParams.get('host'), `/cloudsql/${connectionName}`)
assert.equal(url.searchParams.get('password'), 'test/password')
assert.equal(inputs.get('SecretServerMasterKey')!.length, 32)
for (const [name, role, caller] of [
['Write', 'write', 'api'],
['Fetch', 'fetch', 'runner'],
]) {
const args = inputs.get(`SecretServer${name}`)!
assert.equal(args.ingress, 'INGRESS_TRAFFIC_INTERNAL_ONLY')
const container = args.template.containers[0]
assert.deepEqual(args.template.volumes, [{ name: 'cloudsql', cloudSqlInstance: { instances: [connectionName] } }])
assert.deepEqual(container.volumeMounts, [{ name: 'cloudsql', mountPath: '/cloudsql' }])
assert.equal(container.image, 'candidate')
assert.equal(container.startupProbe.httpGet.path, '/ready')
const env = Object.fromEntries(container.envs.map((e: any) => [e.name, e.value ?? e.valueSource?.secretKeyRef]))
assert.equal(env.ENVIRONMENT, 'production')
assert.equal(env.SECRET_SERVER_ROLE, role)
assert.equal(env.SECRET_SERVER_AUDIENCE, `https://${args.name}-12345.${region}.run.app`)
assert.equal(endpoints?.[`${role}Url`], env.SECRET_SERVER_AUDIENCE)
assert.deepEqual(args.customAudiences, [env.SECRET_SERVER_AUDIENCE])
assert.equal(env.SECRET_SERVER_AUTH_MODE, 'google')
assert.equal(env.SECRET_MASTER_KEY_BASE64.version, '7')
assert.equal(env.DATABASE_URL.version, '7')
assert.deepEqual(inputs.get(`SecretServer${name}Invoker`)!.members, [`serviceAccount:${caller}@example.test`])
if (role === 'fetch') assert.equal(env.SECRET_SERVER_RUNNER_REGISTRY, runnerRegistry)
else assert.equal(env.SECRET_SERVER_ALLOWED_CALLERS, '[email protected]')
}
for (const name of alarms) {
assert.deepEqual(inputs.get(name)!.notificationChannels, [channel])
}
const policy = inputs.get('SecretServerRunnerVolume')!.conditions[0].conditionThreshold
assert.deepEqual(policy.aggregations[0].groupByFields, ['metric.label.runner_id'])
assert.equal(policy.aggregations[0].alignmentPeriod, '300s')
assert.equal(policy.thresholdValue, 99)
assert.match(inputs.get('SecretServerReplayMetric')!.filter, /Secret credential replay/)
assert.match(inputs.get('SecretServerDecryptFailureMetric')!.filter, /result=decrypt_failed/)
})
test('a scoped retry admits only the registry already installed on the serving Fetch revision', async () => {
const { endpoints } = await provision('dev', undefined, '{"gcp_iit":{"67890":"existing-runner"}}')
assert.deepEqual(endpoints?.enrolledIds, ['67890'])
})