The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(api): issue single-use secret credentials for v2 boxes (#2769)
Jiaqiang Wongbc78b36e5dc2
diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.tsindex d0462bbec..785c04942 100644--- a/apps/api/src/app.module.ts+++ b/apps/api/src/app.module.ts@@ -57,7 +57,7 @@ import { McpModule } from './mcp/mcp.module'pinoHttp: {autoLogging: logConfig.requests.enabled,level: logConfig.level,- redact: ['req.headers.authorization', 'req.body.turnstileToken'],+ redact: ['req.headers.authorization', 'req.body.turnstileToken', 'req.body.token'],hooks: {logMethod: swapMessageAndObject,},diff --git a/apps/api/src/box/box.module.ts b/apps/api/src/box/box.module.tsindex 40a82ec29..ef78e74fa 100644--- a/apps/api/src/box/box.module.ts+++ b/apps/api/src/box/box.module.ts@@ -5,6 +5,8 @@*/import { Module } from '@nestjs/common'+import { SecretCredentialService } from './services/secret-credential.service'+import { SecretCredentialController } from './controllers/secret-credential.controller'import { DataSource } from 'typeorm'import { BoxController } from './controllers/box.controller'import { BoxService } from './services/box.service'@@ -111,6 +113,7 @@ import { GcpDiskClient } from './services/gcp-disk-client']),],controllers: [+ SecretCredentialController,BoxController,RunnerController,PreviewController,@@ -120,6 +123,7 @@ import { GcpDiskClient } from './services/gcp-disk-client'CustomDomainMaintenanceController,],providers: [+ SecretCredentialService,SecretServerClient,CheckpointService,CheckpointArchiveStore,diff --git a/apps/api/src/box/controllers/secret-credential.controller.ts b/apps/api/src/box/controllers/secret-credential.controller.tsnew file mode 100644index 000000000..c9016e3b7--- /dev/null+++ b/apps/api/src/box/controllers/secret-credential.controller.ts@@ -0,0 +1,19 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */+import { Body, Controller, Header, HttpCode, Post } from '@nestjs/common'+import { ApiExcludeController } from '@nestjs/swagger'+import { SecretCredentialService } from '../services/secret-credential.service'++export const SECRET_CREDENTIAL_PATH = 'internal/v1/credentials/introspect'++@ApiExcludeController()+@Controller(SECRET_CREDENTIAL_PATH)+export class SecretCredentialController {+ constructor(private readonly credentials: SecretCredentialService) {}++ @Post()+ @HttpCode(200)+ @Header('Cache-Control', 'no-store')+ introspect(@Body() body: { token?: unknown; runner_id?: unknown } | undefined) {+ return this.credentials.consume(body?.token, body?.runner_id)+ }+}diff --git a/apps/api/src/box/managers/box-migration.manager.pool.integration.spec.ts b/apps/api/src/box/managers/box-migration.manager.pool.integration.spec.tsindex 94a209cf1..75e72a793 100644--- a/apps/api/src/box/managers/box-migration.manager.pool.integration.spec.ts+++ b/apps/api/src/box/managers/box-migration.manager.pool.integration.spec.ts@@ -9,6 +9,7 @@ import { CustomNamingStrategy } from '../../common/utils/naming-strategy.util'import { Box } from '../entities/box.entity'import { BoxLastActivity } from '../entities/box-last-activity.entity'import { BoxMigration } from '../entities/box-migration.entity'+import { JobService } from '../services/job.service'import { Job } from '../entities/job.entity'import { BoxDesiredState } from '../enums/box-desired-state.enum'import { BoxMigrationState } from '../enums/box-migration-state.enum'@@ -39,6 +40,8 @@ describeIfDatabase('BoxMigrationManager import submission (integration, single-clet migrations: Repository<BoxMigration>let jobs: Repository<Job>let ownsSchema = false+ let observer: DataSource+ const notifications: boolean[] = []beforeAll(async () => {dataSource = await new DataSource({@@ -69,6 +72,7 @@ describeIfDatabase('BoxMigrationManager import submission (integration, single-cboxes = dataSource.getRepository(Box)migrations = dataSource.getRepository(BoxMigration)jobs = dataSource.getRepository(Job)+ observer = await new DataSource({ ...dataSource.options, entities: [] } as any).initialize()})afterAll(async () => {@@ -80,6 +84,7 @@ describeIfDatabase('BoxMigrationManager import submission (integration, single-cawait dataSource.query(`DROP SCHEMA IF EXISTS "${schemaName}" CASCADE`)}} finally {+ await observer?.destroy()await dataSource.destroy()}})@@ -117,8 +122,8 @@ describeIfDatabase('BoxMigrationManager import submission (integration, single-c/*** The manager with real Postgres and stubs that keep the connection behaviour* honest: the scheduler stub queries through the same DataSource (as- * `RunnerService.getRandomAvailableRunner` does), and the job stub writes- * through the entity manager it is handed (as `JobService.createJob` does).+ * `RunnerService.getRandomAvailableRunner` does), and the real JobService writes+ * through that transaction. An independent observer checks notification visibility.*/function makeManager(): BoxMigrationManager {const runnerService = {@@ -127,13 +132,16 @@ describeIfDatabase('BoxMigrationManager import submission (integration, single-creturn { id: targetRunnerId }},} as any- const jobService = {- createJob: async (manager: any, type: JobType, runnerId: string, resourceType: any, resourceId: string) => {- const job = new Job({ type, runnerId, resourceType, resourceId })- await manager.getRepository(Job).insert(job)- return job- },- } as any+ const jobService = new JobService(+ jobs,+ {+ lpush: async (_queue: string, id: string) => {+ const [row] = await observer.query('SELECT EXISTS (SELECT 1 FROM job WHERE id=$1) AS visible', [id])+ notifications.push(row.visible)+ },+ } as any,+ {} as any,+ )const redisLockProvider = {lock: async () => true,unlock: async () => undefined,@@ -159,6 +167,7 @@ describeIfDatabase('BoxMigrationManager import submission (integration, single-cexpect(outcome).toBe('completed')const job = await jobs.findOneByOrFail({ resourceId: box.id })+ expect(notifications).toEqual([true])expect(job.type).toBe(JobType.IMPORT_BOX)expect(job.runnerId).toBe(targetRunnerId)},diff --git a/apps/api/src/box/managers/box-migration.manager.spec.ts b/apps/api/src/box/managers/box-migration.manager.spec.tsindex b5a097cd9..a58838062 100644--- a/apps/api/src/box/managers/box-migration.manager.spec.ts+++ b/apps/api/src/box/managers/box-migration.manager.spec.ts@@ -117,7 +117,8 @@ function makeHarness(}),} as anyconst jobService = {- createJob: jest.fn().mockResolvedValue(undefined),+ createJob: jest.fn().mockResolvedValue({ id: 'job', runnerId: TARGET_RUNNER }),+ notifyRunner: jest.fn().mockResolvedValue(undefined),} as anyconst redisLockProvider = {lock: jest.fn().mockResolvedValue(true),diff --git a/apps/api/src/box/managers/box-migration.manager.ts b/apps/api/src/box/managers/box-migration.manager.tsindex 3ab8a8fba..e5fe758fa 100644--- a/apps/api/src/box/managers/box-migration.manager.ts+++ b/apps/api/src/box/managers/box-migration.manager.ts@@ -10,6 +10,7 @@ import { DataSource, EntityManager, FindOptionsWhere, IsNull, Not } from 'typeorimport { setTimeout } from 'timers/promises'import { RedisLockProvider } from '../common/redis-lock.provider'+import { Job } from '../entities/job.entity'import { Box } from '../entities/box.entity'import { BoxMigration } from '../entities/box-migration.entity'import { BoxMigrationState } from '../enums/box-migration-state.enum'@@ -287,6 +288,7 @@ export class BoxMigrationManager implements TrackableJobExecutions, OnApplicatio}let submitted = false+ let job: Job | undefinedtry {// Resolved BEFORE the transaction opens, never inside it. The import's// resolver asks the scheduler for a target runner, which is a query: from@@ -324,7 +326,7 @@ export class BoxMigrationManager implements TrackableJobExecutions, OnApplicatioreturn false}- await this.jobService.createJob(+ job = await this.jobService.createJob(entityManager,jobType,target.runnerId,@@ -336,6 +338,7 @@ export class BoxMigrationManager implements TrackableJobExecutions, OnApplicatiothis.logger.log(`Submitted ${jobType} for box ${box.id} to runner ${target.runnerId}`)return true})+ if (submitted && job) await this.jobService.notifyRunner(job.runnerId, job.id)} catch (error) {this.logger.error(`Error submitting ${jobType} for box ${migration.boxId}:`, error)} finally {diff --git a/apps/api/src/box/repositories/box.repository.ts b/apps/api/src/box/repositories/box.repository.tsindex 1eae494b7..5cee17c9b 100644--- a/apps/api/src/box/repositories/box.repository.ts+++ b/apps/api/src/box/repositories/box.repository.ts@@ -394,6 +394,7 @@ export class BoxRepository extends BaseRepository<Box> {box.assertValid()box.enforceInvariants()await manager.save(Box, box)+ await manager.query('DELETE FROM secret_credential WHERE box_id = $1', [box.id])return { box, previous }})this.emitUpdateEvents(changed.box, changed.previous)@@ -474,6 +475,9 @@ export class BoxRepository extends BaseRepository<Box> {const invariantChanges = box.enforceInvariants()await entityManager.update(Box, id, { ...updateData, ...invariantChanges })+ if (box.desiredState === BoxDesiredState.DESTROYED) {+ await entityManager.query('DELETE FROM secret_credential WHERE box_id = $1', [id])+ }box.updatedAt = new Date()if (previousBox.state !== box.state || previousBox.organizationId !== box.organizationId) {diff --git a/apps/api/src/box/runner-adapter/runnerAdapter.credentials.spec.ts b/apps/api/src/box/runner-adapter/runnerAdapter.credentials.spec.tsnew file mode 100644index 000000000..6d931a652--- /dev/null+++ b/apps/api/src/box/runner-adapter/runnerAdapter.credentials.spec.ts@@ -0,0 +1,53 @@+import { RunnerAdapterV0 } from './runnerAdapter.v0'+import { RunnerAdapterV2 } from './runnerAdapter.v2'++describe('Secret credential rollout', () => {+ const reference = {+ name: 'key',+ secretId: '00000000-0000-4000-8000-000000000001',+ hosts: ['example.com'],+ headers: { authorization: '{value}' },+ }+ const inline = { name: 'key', value: 'private', hosts: ['example.com'], headers: { authorization: '{value}' } }++ it.each([+ [true, [inline]],+ [false, [reference]],+ ])('rejects inconsistent v2 flag %s and stored secrets', async (enabled, secrets) => {+ const jobs = { createJob: jest.fn() }+ const issue = jest.fn()+ const adapter = new RunnerAdapterV2({} as any, {} as any, jobs as any)+ Object.assign(adapter, { config: { get: () => enabled }, credentials: { issue } })+ await adapter.init({ id: 'runner' } as any)+ await expect(adapter.createBox({ id: 'box', secrets } as any, 'base')).rejects.toThrow(/Secret/)+ expect(issue).not.toHaveBeenCalled()+ expect(jobs.createJob).not.toHaveBeenCalled()+ })++ it('does not issue credentials for empty boxes or START_BOX', async () => {+ const jobs = { createJob: jest.fn() }+ const issue = jest.fn()+ const adapter = new RunnerAdapterV2({} as any, {} as any, jobs as any)+ Object.assign(adapter, { config: { get: () => true }, credentials: { issue } })+ await adapter.init({ id: 'runner' } as any)+ await adapter.createBox({ id: 'box', secrets: [] } as any, 'base')+ await adapter.startBox('box', 'auth')+ expect(issue).not.toHaveBeenCalled()+ for (const call of jobs.createJob.mock.calls) expect(call[5]).not.toHaveProperty('secretCredential')+ })++ it.each([+ [true, reference],+ [false, reference],+ [true, inline],+ ])('rejects v0 create and recovery with flag %s', async (enabled, secret) => {+ const adapter = new RunnerAdapterV0()+ const client = { create: jest.fn(), recover: jest.fn() }+ Object.assign(adapter, { config: { get: () => enabled }, boxApiClient: client })+ const box = { id: 'box', secrets: [secret] } as any+ await expect(adapter.createBox(box, 'base')).rejects.toThrow('v2 runner')+ await expect(adapter.recoverBox(box)).rejects.toThrow('v2 runner')+ expect(client.create).not.toHaveBeenCalled()+ expect(client.recover).not.toHaveBeenCalled()+ })+})diff --git a/apps/api/src/box/runner-adapter/runnerAdapter.v0.nested-allowlist.spec.ts b/apps/api/src/box/runner-adapter/runnerAdapter.v0.nested-allowlist.spec.tsindex 8d1576359..a042fde76 100644--- a/apps/api/src/box/runner-adapter/runnerAdapter.v0.nested-allowlist.spec.ts+++ b/apps/api/src/box/runner-adapter/runnerAdapter.v0.nested-allowlist.spec.ts@@ -26,6 +26,7 @@ describe('Runner V0 internal nesting wire contract', () => {await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))try {const adapter = new RunnerAdapterV0()+ Object.assign(adapter, { config: { get: () => false } })const runner = new Runner({region: 'local',name: 'test',diff --git a/apps/api/src/box/runner-adapter/runnerAdapter.v0.spec.ts b/apps/api/src/box/runner-adapter/runnerAdapter.v0.spec.tsindex 80adec802..2c85a50f0 100644--- a/apps/api/src/box/runner-adapter/runnerAdapter.v0.spec.ts+++ b/apps/api/src/box/runner-adapter/runnerAdapter.v0.spec.ts@@ -8,6 +8,7 @@ import { RunnerAdapterV0 } from './runnerAdapter.v0'describe('RunnerAdapterV0 createBox', () => {it.each([0.125, 0.126, 1.001, 1.5, 16])('preserves %s CPUs in create and recover requests', async (cpu) => {const adapter = new RunnerAdapterV0()+ Object.assign(adapter, { config: { get: () => false } })const create = jest.fn().mockResolvedValue({ data: {} })const recover = jest.fn().mockResolvedValue(undefined);(adapter as any).boxApiClient = { create, recover }@@ -21,6 +22,7 @@ describe('RunnerAdapterV0 createBox', () => {})it.each([false, true])('forwards persisted guest privilege %s to the runner', async (privileged) => {const adapter = new RunnerAdapterV0()+ Object.assign(adapter, { config: { get: () => false } })await adapter.init({ id: 'runner-1', apiUrl: 'http://runner.invalid', supportsPrivileged: true } as any)const create = jest.fn().mockResolvedValue({ data: { daemonVersion: '1.0' } });(adapter as any).boxApiClient = { create }@@ -34,6 +36,7 @@ describe('RunnerAdapterV0 createBox', () => {// networkBlockAll / networkAllowList pair is gone from the wire.it('sends the outbound policy as the enabled flag and entries', async () => {const adapter = new RunnerAdapterV0()+ Object.assign(adapter, { config: { get: () => false } })const create = jest.fn().mockResolvedValue({ data: { daemonVersion: '1.0' } });(adapter as any).boxApiClient = { create }@@ -57,6 +60,7 @@ describe('RunnerAdapterV0 createBox', () => {it('passes secrets through to the runner create body', async () => {const adapter = new RunnerAdapterV0()+ Object.assign(adapter, { config: { get: () => false } })const create = jest.fn().mockResolvedValue({ data: { daemonVersion: '1.0' } });(adapter as any).boxApiClient = { create }@@ -105,6 +109,7 @@ describe('RunnerAdapterV0 createBox', () => {/** The caller may pin a curated tag to the build this runner already has. */it('sends the image it is handed rather than the one on the box', async () => {const adapter = new RunnerAdapterV0()+ Object.assign(adapter, { config: { get: () => false } })const create = jest.fn().mockResolvedValue({ data: { daemonVersion: '1.0' } });(adapter as any).boxApiClient = { create }const pinned = `ghcr.io/boxlite-ai/boxlite-agent-base@sha256:${'a'.repeat(64)}`@@ -116,6 +121,7 @@ describe('RunnerAdapterV0 createBox', () => {it('passes secrets through to the runner recover body', async () => {const adapter = new RunnerAdapterV0()+ Object.assign(adapter, { config: { get: () => false } })const recover = jest.fn().mockResolvedValue(undefined);(adapter as any).boxApiClient = { recover }@@ -148,6 +154,7 @@ describe('RunnerAdapterV0 createBox', () => {describe('RunnerAdapterV0 recoverBox', () => {it.each([false, true])('forwards persisted guest privilege %s to the recover request', async (privileged) => {const adapter = new RunnerAdapterV0()+ Object.assign(adapter, { config: { get: () => false } })await adapter.init({ id: 'runner-1', apiUrl: 'http://runner.invalid', supportsPrivileged: true } as any)const recover = jest.fn().mockResolvedValue(undefined);(adapter as any).boxApiClient = { recover }@@ -163,6 +170,7 @@ describe('RunnerAdapterV0 privilege support', () => {'rejects privileged create and recovery when runner support is %s',async (supportsPrivileged) => {const adapter = new RunnerAdapterV0()+ Object.assign(adapter, { config: { get: () => false } })await adapter.init({ id: 'runner-1', apiUrl: 'http://runner.invalid', supportsPrivileged } as any)const create = jest.fn().mockResolvedValue({ data: {} })const recover = jest.fn().mockResolvedValue(undefined)@@ -178,6 +186,7 @@ describe('RunnerAdapterV0 privilege support', () => {it('preserves the capability returned by runner info', async () => {const adapter = new RunnerAdapterV0()+ Object.assign(adapter, { config: { get: () => false } });(adapter as any).runnerApiClient = {runnerInfo: jest.fn().mockResolvedValue({ data: { supportsPrivileged: true } }),}@@ -191,6 +200,7 @@ describe('RunnerAdapterV0 updateNetworkSettings', () => {// recover; the Daytona-era flag pair is not sent.it('sends the outbound policy as the enabled flag and entries', async () => {const adapter = new RunnerAdapterV0()+ Object.assign(adapter, { config: { get: () => false } })const updateNetworkSettings = jest.fn().mockResolvedValue(undefined);(adapter as any).boxApiClient = { updateNetworkSettings }diff --git a/apps/api/src/box/runner-adapter/runnerAdapter.v0.ts b/apps/api/src/box/runner-adapter/runnerAdapter.v0.tsindex de6c0a44d..7cecfc05d 100644--- a/apps/api/src/box/runner-adapter/runnerAdapter.v0.ts+++ b/apps/api/src/box/runner-adapter/runnerAdapter.v0.ts@@ -8,7 +8,8 @@ import axios, { AxiosError } from 'axios'import axiosDebug from 'axios-debug-log'import axiosRetry from 'axios-retry'-import { Injectable, Logger } from '@nestjs/common'+import { Inject, Injectable, Logger } from '@nestjs/common'+import { TypedConfigService } from '../../config/typed-config.service'import { RunnerAdapter, RunnerInfo, RunnerBoxInfo, StartBoxResponse } from './runnerAdapter'import { Runner } from '../entities/runner.entity'import {@@ -120,6 +121,17 @@ export function sanitizedNonJsonRunnerMessage(data: unknown): string {@Injectable()export class RunnerAdapterV0 implements RunnerAdapter {+ @Inject(TypedConfigService)+ private readonly config: TypedConfigService++ private rejectSecretReferences(box: Box): void {+ if (+ box.secrets?.length &&+ (this.config.get('secretServer.enabled') || box.secrets.some((s) => s.secretId !== undefined))+ ) {+ throw new Error('Secret Server secrets require a v2 runner')+ }+ }private readonly logger = new Logger(RunnerAdapterV0.name)private boxApiClient: BoxApiprivate runnerApiClient: DefaultApi@@ -260,6 +272,7 @@ export class RunnerAdapterV0 implements RunnerAdapter {metadata?: { [key: string]: string },nestedVirtualization = false,): Promise<StartBoxResponse | undefined> {+ this.rejectSecretReferences(box)if (box.privileged && !this.runner.supportsPrivileged) {throw new Error(`Runner ${this.runner.id} does not support privileged Boxes`)}@@ -342,6 +355,7 @@ export class RunnerAdapterV0 implements RunnerAdapter {}async recoverBox(box: Box): Promise<void> {+ this.rejectSecretReferences(box)if (box.privileged && !this.runner.supportsPrivileged) {throw new Error(`Runner ${this.runner.id} does not support privileged Boxes`)}diff --git a/apps/api/src/box/runner-adapter/runnerAdapter.v2.nested.spec.ts b/apps/api/src/box/runner-adapter/runnerAdapter.v2.nested.spec.tsindex 00fb7a495..a7ebf43eb 100644--- a/apps/api/src/box/runner-adapter/runnerAdapter.v2.nested.spec.ts+++ b/apps/api/src/box/runner-adapter/runnerAdapter.v2.nested.spec.ts@@ -17,6 +17,7 @@ describe('V2 optional nesting contract', () => {}// The repository is supplied by Nest in production.const adapter = new RunnerAdapterV2({} as any, {} as any, jobs as any)+ Object.assign(adapter, { config: { get: () => false } })Object.assign(adapter, { runnerRepository: repository })void adapter.init({ id: 'runner', apiVersion: '2' } as any)return { adapter, jobs, repository }diff --git a/apps/api/src/box/runner-adapter/runnerAdapter.v2.spec.ts b/apps/api/src/box/runner-adapter/runnerAdapter.v2.spec.tsindex df22950b7..ed9e4362f 100644--- a/apps/api/src/box/runner-adapter/runnerAdapter.v2.spec.ts+++ b/apps/api/src/box/runner-adapter/runnerAdapter.v2.spec.ts@@ -11,6 +11,7 @@ describe('RunnerAdapterV2 createBox', () => {it.each([0.125, 0.126, 1.001, 1.5, 16])('preserves %s CPUs in the create job', async (cpu) => {const jobService = { createJob: jest.fn().mockResolvedValue(undefined) } as anyconst adapter = new RunnerAdapterV2({} as any, {} as any, jobService)+ Object.assign(adapter, { config: { get: () => false } })await adapter.init({ id: 'runner-1' } as any)await adapter.createBox({ id: 'box-cpu', cpu } as any, 'base')@@ -27,6 +28,7 @@ describe('RunnerAdapterV2 createBox', () => {it.each([false, true])('forwards persisted guest privilege %s to the create job', async (privileged) => {const jobService = { createJob: jest.fn().mockResolvedValue(undefined) } as anyconst adapter = new RunnerAdapterV2({} as any, {} as any, jobService)+ Object.assign(adapter, { config: { get: () => false } })await adapter.init({ id: 'runner-1', supportsPrivileged: true } as any)await adapter.createBox({ id: 'box-1', image: 'base', privileged } as any, 'base')@@ -44,6 +46,7 @@ describe('RunnerAdapterV2 createBox', () => {it.each([undefined, false])('rejects privileged create when runner support is %s', async (supportsPrivileged) => {const jobService = { createJob: jest.fn().mockResolvedValue(undefined) } as anyconst adapter = new RunnerAdapterV2({} as any, {} as any, jobService)+ Object.assign(adapter, { config: { get: () => false } })await adapter.init({ id: 'runner-1', supportsPrivileged } as any)await expect(adapter.createBox({ id: 'box-1', privileged: true } as any, 'base')).rejects.toThrow(@@ -55,6 +58,7 @@ describe('RunnerAdapterV2 createBox', () => {it('passes secrets through to the CREATE_BOX job payload', async () => {const jobService = { createJob: jest.fn().mockResolvedValue(undefined) } as anyconst adapter = new RunnerAdapterV2({} as any, {} as any, jobService)+ Object.assign(adapter, { config: { get: () => false } })await adapter.init({ id: 'runner-1' } as any)const box = {@@ -108,6 +112,7 @@ describe('RunnerAdapterV2 createBox', () => {it('sends the image it is handed rather than the one on the box', async () => {const jobService = { createJob: jest.fn().mockResolvedValue(undefined) } as anyconst adapter = new RunnerAdapterV2({} as any, {} as any, jobService)+ Object.assign(adapter, { config: { get: () => false } })await adapter.init({ id: 'runner-1' } as any)const pinned = `ghcr.io/boxlite-ai/boxlite-agent-base@sha256:${'a'.repeat(64)}`@@ -126,6 +131,7 @@ describe('RunnerAdapterV2 createBox', () => {it('puts the outbound policy in the CREATE_BOX job payload as the enabled flag and entries', async () => {const jobService = { createJob: jest.fn().mockResolvedValue(undefined) } as anyconst adapter = new RunnerAdapterV2({} as any, {} as any, jobService)+ Object.assign(adapter, { config: { get: () => false } })await adapter.init({ id: 'runner-1' } as any)await adapter.createBox(diff --git a/apps/api/src/box/runner-adapter/runnerAdapter.v2.ts b/apps/api/src/box/runner-adapter/runnerAdapter.v2.tsindex ee35d233d..8b8921e93 100644--- a/apps/api/src/box/runner-adapter/runnerAdapter.v2.ts+++ b/apps/api/src/box/runner-adapter/runnerAdapter.v2.ts@@ -4,7 +4,9 @@* SPDX-License-Identifier: AGPL-3.0*/-import { Injectable, Logger } from '@nestjs/common'+import { Inject, Injectable, Logger } from '@nestjs/common'+import { TypedConfigService } from '../../config/typed-config.service'+import { SecretCredentialService } from '../services/secret-credential.service'import { InjectRepository } from '@nestjs/typeorm'import { Repository, IsNull } from 'typeorm'import { RunnerAdapter, RunnerInfo, RunnerBoxInfo, StartBoxResponse } from './runnerAdapter'@@ -27,6 +29,11 @@ import { RunnerState } from '../enums/runner-state.enum'*/@Injectable()export class RunnerAdapterV2 implements RunnerAdapter {+ @Inject(TypedConfigService)+ private readonly config: TypedConfigService++ @Inject(SecretCredentialService)+ private readonly credentials: SecretCredentialServiceprivate readonly logger = new Logger(RunnerAdapterV2.name)private runner: Runner@@ -138,6 +145,14 @@ export class RunnerAdapterV2 implements RunnerAdapter {if (box.privileged && !this.runner.supportsPrivileged) {throw new Error(`Runner ${this.runner.id} does not support privileged Boxes`)}+ const enabled = this.config.get('secretServer.enabled')+ const secrets = box.secrets ?? []+ if (!enabled && secrets.some((secret) => secret.secretId !== undefined)) {+ throw new Error('Secret references require Secret Server to be enabled')+ }+ if (enabled && secrets.some((secret) => !secret.secretId)) {+ throw new Error('Secret Server requires secret references; migrate inline secrets before enabling')+ }const payload = {id: box.id,...(nestedVirtualization ? { nestedVirtualization: true } : {}),@@ -160,7 +175,7 @@ export class RunnerAdapterV2 implements RunnerAdapter {})),secrets: box.secrets?.map((secret) => ({name: secret.name,- value: secret.value,+ ...(!enabled ? { value: secret.value } : {}),hosts: secret.hosts,placeholder: secret.placeholder,headers: secret.headers,@@ -173,7 +188,26 @@ export class RunnerAdapterV2 implements RunnerAdapter {regionId: box.region,}- await this.jobService.createJob(null, JobType.CREATE_BOX, this.runner.id, ResourceType.BOX, box.id, payload)+ if (enabled && secrets.length) {+ const job = await this.jobRepository.manager.transaction(async (manager) => {+ const secretCredential = await this.credentials.issue(+ {+ runnerId: this.runner.id,+ boxId: box.id,+ organizationId: box.organizationId,+ secretIds: secrets.map((secret) => secret.secretId),+ },+ manager,+ )+ return this.jobService.createJob(manager, JobType.CREATE_BOX, this.runner.id, ResourceType.BOX, box.id, {+ ...payload,+ secretCredential,+ })+ })+ await this.jobService.notifyRunner(job.runnerId, job.id)+ } else {+ await this.jobService.createJob(null, JobType.CREATE_BOX, this.runner.id, ResourceType.BOX, box.id, payload)+ }this.logger.debug(`Created CREATE_BOX job for box ${box.id} on runner ${this.runner.id}`)diff --git a/apps/api/src/box/services/checkpoint-recover.service.ts b/apps/api/src/box/services/checkpoint-recover.service.tsindex 644429e47..82b33a4e9 100644--- a/apps/api/src/box/services/checkpoint-recover.service.ts+++ b/apps/api/src/box/services/checkpoint-recover.service.ts@@ -16,6 +16,7 @@ import { BoxCheckpointState } from '../entities/box-checkpoint-state.entity'import { Runner } from '../entities/runner.entity'import { Checkpoint } from '../entities/checkpoint.entity'import { CheckpointOperation } from '../entities/checkpoint-operation.entity'+import { Job } from '../entities/job.entity'import { JobType } from '../enums/job-type.enum'import { ResourceType } from '../enums/resource-type.enum'import { RunnerState } from '../enums/runner-state.enum'@@ -71,7 +72,8 @@ export class CheckpointRecoverService {const persist = async (candidate: string) => {box.name = candidatelet checkpoint: Checkpoint- return this.boxes.insert(+ let job: Job+ const created = await this.boxes.insert(box,maxCreatedBoxes,undefined,@@ -90,10 +92,12 @@ export class CheckpointRecoverService {this.assertRunner(currentRunner, checkpoint)},async (manager) => {- await this.schedule(manager, checkpoint, box, manager.create(BoxCheckpointState, { boxId: box.id }))+ job = await this.schedule(manager, checkpoint, box, manager.create(BoxCheckpointState, { boxId: box.id }))await manager.save(Box, box)},)+ await this.jobs.notifyRunner(job!.runnerId, job!.id)+ return created}try {const created = name === undefined ? await persistWithGeneratedBoxName(box.id, persist) : await persist(name)@@ -148,7 +152,7 @@ export class CheckpointRecoverService {checkpoint: Checkpoint,box: Box,checkpointState: BoxCheckpointState,- ): Promise<void> {+ ): Promise<Job> {const operation = manager.create(CheckpointOperation, {id: randomUUID(),organizationId: box.organizationId,@@ -182,5 +186,6 @@ export class CheckpointRecoverService {pending: true,errorReason: null,})+ return job}}diff --git a/apps/api/src/box/services/checkpoint.integration.spec.ts b/apps/api/src/box/services/checkpoint.integration.spec.tsindex 2a91d3941..7c2389a5d 100644--- a/apps/api/src/box/services/checkpoint.integration.spec.ts+++ b/apps/api/src/box/services/checkpoint.integration.spec.ts@@ -1,3 +1,5 @@+import { SecretCredentialService } from './secret-credential.service'+import { AddSecretCredential1794873600000 } from '../../migrations/pre-deploy/1794873600000-add-secret-credential-migration'// Copyright 2026 BoxLite AI// SPDX-License-Identifier: AGPL-3.0@@ -68,6 +70,7 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>const archiveStore = { remove: jest.fn() }let settings: { archivePrefix?: string; maxPerOrganization: number; enabled?: boolean }const cache = { invalidate: jest.fn() }+ const jobNotifications: { visible: boolean; boxUnlocked: boolean }[] = []const uploadNotifications = { lpush: jest.fn() }beforeAll(async () => {@@ -101,11 +104,38 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>}).initialize()await dataSource.query(`CREATE SCHEMA "${schema}"`)await dataSource.synchronize()+ const migrationRunner = dataSource.createQueryRunner()+ try {+ await new AddSecretCredential1794873600000().up(migrationRunner)+ } finally {+ await migrationRunner.release()+ }checkpoints = dataSource.getRepository(Checkpoint)boxes = dataSource.getRepository(Box)states = dataSource.getRepository(BoxCheckpointState)jobs = dataSource.getRepository(Job)- const jobService = new JobService(jobs, { lpush: jest.fn().mockResolvedValue(1) } as any, {} as any)+ const jobService = new JobService(+ jobs,+ {+ lpush: async (_queue: string, id: string) => {+ const observed = await jobs.findOneBy({ id })+ let boxUnlocked = false+ if (observed) {+ const observer = dataSource.createQueryRunner()+ await observer.startTransaction()+ try {+ await observer.query('SELECT id FROM box WHERE id = $1 FOR UPDATE NOWAIT', [observed.resourceId])+ boxUnlocked = true+ } finally {+ await observer.rollbackTransaction()+ await observer.release()+ }+ }+ jobNotifications.push({ visible: !!observed, boxUnlocked })+ },+ } as any,+ {} as any,+ )const config = { get: (key: string) => (key === 'checkpoint' ? settings : undefined) } as ConfigServiceservice = new CheckpointService(dataSource, config, jobService, cache as any, archiveStore as never)receiver = new CheckpointJobReceiver(@@ -137,6 +167,7 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>})beforeEach(async () => {+ jobNotifications.length = 0uploadNotifications.lpush.mockReset().mockResolvedValue(1)await dataSource.query(`TRUNCATE TABLE "${schema}"."checkpoint_operation", "${schema}"."checkpoint", "${schema}"."job", "${schema}"."box", "${schema}"."runner", "${schema}"."image", "${schema}"."registry_credential" CASCADE`,@@ -231,6 +262,15 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>return service.get(organizationId, checkpoint.id)}+ it('notifies checkpoint export and import only after their transactions commit', async () => {+ const checkpoint = await readyCheckpoint()+ await recovery.createBox(organization, checkpoint.id, 'notification-target', undefined)+ expect(jobNotifications).toEqual([+ { visible: true, boxUnlocked: true },+ { visible: true, boxUnlocked: true },+ ])+ })+it('preserves exact MiB through checkpoint capture and new-Box recovery', async () => {const original = await source('memory-source')Object.assign(original, { mem: 1, memoryMib: 300 })@@ -779,9 +819,17 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>const operation = await dataSource.getRepository(CheckpointOperation).findOneByOrFail({ jobId: created.activeJobId! })+ const credentials = new SecretCredentialService(dataSource)+ const issued = await credentials.issue({+ boxId: created.id,+ runnerId: created.runnerId,+ organizationId,+ secretIds: [randomUUID()],+ })const deleted = await lifecycleService().destroy(created.id, organizationId, Context.user()).then(withCheckpointState)+ expect(await credentials.consume(issued.token, created.runnerId)).toEqual({ active: false })expect(deleted).toMatchObject({desiredState: BoxDesiredState.DESTROYED,pending: true,diff --git a/apps/api/src/box/services/checkpoint.service.ts b/apps/api/src/box/services/checkpoint.service.tsindex 486b7da52..8a6f12aab 100644--- a/apps/api/src/box/services/checkpoint.service.ts+++ b/apps/api/src/box/services/checkpoint.service.ts@@ -141,6 +141,7 @@ export class CheckpointService {sourceBox = boxreturn checkpoint})+ await this.jobs.notifyRunner(checkpoint.sourceRunnerId, checkpoint.exportJobId!)if (sourceBox) this.cache.invalidate(sourceBox)return checkpoint} catch (error) {diff --git a/apps/api/src/box/services/credential-lifecycle.integration.spec.ts b/apps/api/src/box/services/credential-lifecycle.integration.spec.tsnew file mode 100644index 000000000..bb24b1181--- /dev/null+++ b/apps/api/src/box/services/credential-lifecycle.integration.spec.ts@@ -0,0 +1,274 @@+import { randomUUID } from 'node:crypto'+import { DataSource } from 'typeorm'+import { AddSecretCredential1794873600000 } from '../../migrations/pre-deploy/1794873600000-add-secret-credential-migration'+import { SecretCredentialService } from './secret-credential.service'+import { BoxService } from './box.service'+import { JobService } from './job.service'+import { Job } from '../entities/job.entity'+import { RunnerAdapterV2 } from '../runner-adapter/runnerAdapter.v2'+import { JobType } from '../enums/job-type.enum'+import { ResourceType } from '../enums/resource-type.enum'+import { JobConflictError } from '../errors/job-conflict.error'+import { BoxState } from '../enums/box-state.enum'+import { BoxDesiredState } from '../enums/box-desired-state.enum'+import { Box } from '../entities/box.entity'+import { BoxLastActivity } from '../entities/box-last-activity.entity'+import { BoxCheckpointState } from '../entities/box-checkpoint-state.entity'+import { BoxRepository } from '../repositories/box.repository'+import { Context } from '../../common/context/context'+;(process.env.DB_HOST ? describe : describe.skip)('Credential lifecycle transactions', () => {+ let db: DataSource+ let credentials: SecretCredentialService+ let repository: BoxRepository+ let box: Box+ const schema = `credential_lifecycle_${randomUUID().replaceAll('-', '')}`+ const binding = {+ runnerId: randomUUID(),+ boxId: 'box-review',+ organizationId: randomUUID(),+ secretIds: [randomUUID()],+ }+ beforeAll(async () => {+ db = await new DataSource({+ type: 'postgres',+ host: process.env.DB_HOST,+ port: Number(process.env.DB_PORT || 5432),+ username: process.env.DB_USERNAME,+ password: process.env.DB_PASSWORD,+ database: process.env.DB_DATABASE,+ schema,+ entities: [Job, Box, BoxLastActivity, BoxCheckpointState],+ entitySkipConstructor: true,+ extra: { application_name: schema, options: `-c search_path=${schema},public` },+ }).initialize()+ await db.query(`CREATE SCHEMA "${schema}"`)+ await db.synchronize()+ await db.query(+ 'CREATE TABLE organization_activation_facts ("organizationId" uuid PRIMARY KEY, "lastBoxCreatedAt" timestamptz, "lastBoxModifiedAt" timestamptz)',+ )+ repository = new BoxRepository(+ db,+ { emit: jest.fn() } as any,+ { invalidate: jest.fn(), invalidateOrgId: jest.fn() } as any,+ )+ const qr = db.createQueryRunner()+ try {+ await new AddSecretCredential1794873600000().up(qr)+ } finally {+ await qr.release()+ }+ credentials = new SecretCredentialService(db)+ })+ beforeEach(async () => {+ await db.query('TRUNCATE box CASCADE')+ await db.query('TRUNCATE job')+ box = new Box('us', 'credential-test')+ Object.assign(box, {+ organizationId: binding.organizationId,+ runnerId: binding.runnerId,+ osUser: 'root',+ labels: {},+ pending: false,+ state: BoxState.STOPPED,+ desiredState: BoxDesiredState.STOPPED,+ })+ await db.getRepository(Box).save(box)+ binding.boxId = box.id+ })+ afterAll(async () => {+ if (db?.isInitialized) {+ await db.query(`DROP SCHEMA "${schema}" CASCADE`)+ await db.destroy()+ }+ })+ function lifecycleService(): BoxService {+ const boxes = Object.create(BoxService.prototype)+ Object.assign(boxes, {+ findOneByIdOrName: async () => repository.findOneBy({ id: box.id }),+ boxRepository: repository,+ eventEmitter: { emit: jest.fn() },+ })+ return boxes+ }+ it('deleted Box credential should be inactive', async () => {+ const issued = await credentials.issue(binding)+ await lifecycleService().destroy(box.id, box.organizationId, Context.user())+ expect((await db.query('SELECT "desiredState" FROM box'))[0].desiredState).toBe(BoxDesiredState.DESTROYED)+ expect(await credentials.consume(issued.token, binding.runnerId)).toEqual({ active: false })+ })+ it('duplicate rejected job should leave exactly one credential', async () => {+ const jobs = new JobService(db.getRepository(Job), { lpush: jest.fn() } as any, {} as any)+ const adapter = new RunnerAdapterV2(repository, db.getRepository(Job), jobs)+ Object.assign(adapter, { config: { get: () => true }, credentials })+ await adapter.init({ id: binding.runnerId } as any)+ const box = {+ id: binding.boxId,+ organizationId: binding.organizationId,+ secrets: [{ secretId: binding.secretIds[0], name: 'review' }],+ } as any+ await adapter.createBox(box, 'base')+ await expect(adapter.createBox(box, 'base')).rejects.toBeInstanceOf(JobConflictError)+ expect(await db.getRepository(Job).count()).toBe(1)+ expect((await db.query('SELECT id FROM secret_credential')).length).toBe(1)+ })+ it('refuses issuance after deletion without inserting a credential', async () => {+ await lifecycleService().destroy(box.id, box.organizationId, Context.user())+ await expect(credentials.issue(binding)).rejects.toThrow('Could not issue secret credential')+ expect(await db.query('SELECT id FROM secret_credential')).toEqual([])+ })++ it.each(['runnerId', 'organizationId'] as const)('refuses a stale %s binding', async (field) => {+ await expect(credentials.issue({ ...binding, [field]: randomUUID() })).rejects.toThrow(+ 'Could not issue secret credential',+ )+ expect(await db.query('SELECT id FROM secret_credential')).toEqual([])+ })++ it('rolls deletion back if credential revocation fails', async () => {+ const issued = await credentials.issue(binding)+ await db.query(`CREATE FUNCTION reject_revocation() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN RAISE EXCEPTION 'test revocation failure'; END $$`)+ await db.query(+ 'CREATE TRIGGER reject_revocation BEFORE DELETE ON secret_credential FOR EACH ROW EXECUTE FUNCTION reject_revocation()',+ )+ try {+ await expect(lifecycleService().destroy(box.id, box.organizationId, Context.user())).rejects.toThrow(+ 'test revocation failure',+ )+ expect((await repository.findOneBy({ id: box.id })).desiredState).toBe(BoxDesiredState.STOPPED)+ expect(await credentials.consume(issued.token, binding.runnerId)).toMatchObject({ active: true })+ } finally {+ await db.query('DROP TRIGGER reject_revocation ON secret_credential')+ await db.query('DROP FUNCTION reject_revocation()')+ }+ })+ it('waits for an in-flight deletion and refuses issuance after it commits', async () => {+ const deletion = db.createQueryRunner()+ await deletion.startTransaction()+ let issuing: Promise<unknown> | undefined+ try {+ await deletion.query('SELECT id FROM box WHERE id = $1 FOR UPDATE', [box.id])+ issuing = credentials.issue(binding).catch((error) => error)+ const deadline = Date.now() + 3000+ let blocked = false+ while (Date.now() < deadline) {+ const [row] = await db.query(+ "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE application_name = $1 AND wait_event_type = 'Lock' AND query LIKE 'SELECT id FROM box WHERE%') AS blocked",+ [schema],+ )+ if (row.blocked) {+ blocked = true+ break+ }+ await new Promise((resolve) => setTimeout(resolve, 10))+ }+ expect(blocked).toBe(true)+ await deletion.query('UPDATE box SET "desiredState" = \'destroyed\' WHERE id = $1', [box.id])+ await deletion.commitTransaction()+ expect(await issuing).toMatchObject({ message: 'Could not issue secret credential' })+ expect(await db.query('SELECT id FROM secret_credential')).toEqual([])+ } finally {+ if (deletion.isTransactionActive) await deletion.rollbackTransaction()+ await deletion.release()+ await issuing+ }+ })+ it.each([true, false])('notifies after job visibility and Box lock release with credentials=%s', async (enabled) => {+ let atNotification: { jobs: number; boxLocked: boolean } | undefined+ const jobs = new JobService(+ db.getRepository(Job),+ {+ lpush: async () => {+ const observer = db.createQueryRunner()+ await observer.startTransaction()+ try {+ const [{ count }] = await observer.query('SELECT count(*)::int FROM job')+ let boxLocked = false+ try {+ await observer.query('SELECT id FROM box WHERE id = $1 FOR UPDATE NOWAIT', [box.id])+ } catch (error) {+ if (error.code !== '55P03') throw error+ boxLocked = true+ }+ atNotification = { jobs: count, boxLocked }+ } finally {+ await observer.rollbackTransaction()+ await observer.release()+ }+ },+ } as any,+ {} as any,+ )+ const adapter = new RunnerAdapterV2(repository, db.getRepository(Job), jobs)+ Object.assign(adapter, { config: { get: () => enabled }, credentials })+ await adapter.init({ id: binding.runnerId } as any)+ await adapter.createBox(+ { ...box, secrets: enabled ? [{ secretId: binding.secretIds[0], name: 'test' }] : [] } as any,+ 'base',+ )+ expect(await db.getRepository(Job).count()).toBe(1)+ expect(atNotification).toEqual({ jobs: 1, boxLocked: false })+ })++ it('revokes by box_id without scanning unrelated credentials', async () => {+ await credentials.issue(binding)+ const other = Object.assign(new Box('us', 'other'), box, {+ id: new Box('us', 'other').id,+ name: 'other',+ authToken: randomUUID(),+ })+ await db.getRepository(Box).save(other)+ await db.query(+ `INSERT INTO secret_credential(token_hash,runner_id,box_id,organization_id,grants,expires_at)+ SELECT decode(md5(i::text),'hex'),$1,$2,$3,'[]'::jsonb,now()+interval '15 minutes'+ FROM generate_series(1,10000) i`,+ [binding.runnerId, other.id, binding.organizationId],+ )+ await db.query('ANALYZE secret_credential')+ const qr = db.createQueryRunner()+ await qr.startTransaction()+ try {+ const rows = await qr.query(+ 'EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) DELETE FROM secret_credential WHERE box_id=$1',+ [box.id],+ )+ const scan = rows[0]['QUERY PLAN'][0].Plan.Plans[0]+ expect(scan['Actual Rows']).toBe(1)+ expect(scan['Node Type']).not.toBe('Seq Scan')+ } finally {+ await qr.rollbackTransaction()+ await qr.release()+ }+ })+ it('does not notify when a transaction rolls back after job insertion', async () => {+ const lpush = jest.fn()+ const jobs = new JobService(db.getRepository(Job), { lpush } as any, {} as any)+ await expect(+ db.transaction(async (manager) => {+ await jobs.createJob(manager, JobType.CREATE_BOX, binding.runnerId, ResourceType.BOX, box.id)+ throw new Error('rollback after insert')+ }),+ ).rejects.toThrow('rollback after insert')+ expect(await db.getRepository(Job).count()).toBe(0)+ expect(lpush).not.toHaveBeenCalled()+ })+ it('retains a discoverable committed job when Redis notification fails', async () => {+ const jobs = new JobService(+ db.getRepository(Job),+ {+ lpush: jest.fn().mockRejectedValue(new Error('Redis unavailable')),+ del: jest.fn(),+ } as any,+ {} as any,+ )+ const adapter = new RunnerAdapterV2(repository, db.getRepository(Job), jobs)+ Object.assign(adapter, { config: { get: () => true }, credentials })+ await adapter.init({ id: binding.runnerId } as any)+ await adapter.createBox({ ...box, secrets: [{ secretId: binding.secretIds[0], name: 'test' }] } as any, 'base')+ const polled = await jobs.pollJobs(binding.runnerId)+ expect(polled).toHaveLength(1)+ expect(polled[0].resourceId).toBe(box.id)+ expect(await db.getRepository(Job).count()).toBe(1)+ expect((await db.query('SELECT id FROM secret_credential')).length).toBe(1)+ })+})diff --git a/apps/api/src/box/services/job.service.credential.spec.ts b/apps/api/src/box/services/job.service.credential.spec.tsnew file mode 100644index 000000000..ecf678ff4--- /dev/null+++ b/apps/api/src/box/services/job.service.credential.spec.ts@@ -0,0 +1,89 @@+import { Logger } from '@nestjs/common'+import { JobService } from './job.service'+import { JobType, ResourceType, JobStatus } from '../dto/job.dto'+import { Job } from '../entities/job.entity'++describe('Credential job lifecycle', () => {+ it('preserves non-CREATE_BOX database failures', async () => {+ const failure = new Error('storage unavailable')+ const service = new JobService({ insert: jest.fn().mockRejectedValue(failure) } as any, {} as any, {} as any)+ const log = jest.spyOn(Logger.prototype, 'error').mockImplementation()+ try {+ await expect(service.createJob(null, JobType.START_BOX, 'runner', ResourceType.BOX, 'box', {})).rejects.toBe(+ failure,+ )+ } finally {+ log.mockRestore()+ }+ })++ it.each([null, JSON.stringify({ image: 'base' })])(+ 'completes a legacy job without a credential: %s',+ async (payload) => {+ const job = new Job({+ type: JobType.CREATE_BOX,+ runnerId: 'runner',+ resourceType: ResourceType.BOX,+ resourceId: 'box',+ status: JobStatus.IN_PROGRESS,+ payload,+ })+ const manager = { findOne: jest.fn().mockResolvedValue(job), save: jest.fn(async (_type, saved) => saved) }+ const service = new JobService(+ { manager: { transaction: (run: any) => run(manager) } } as any,+ {} as any,+ { handleJobCompletion: jest.fn().mockResolvedValue(undefined) } as any,+ )+ await service.updateJobStatus(job.id, JobStatus.COMPLETED)+ expect(manager.save).toHaveBeenCalledWith(Job, job)+ expect(job.payload).toBe(payload)+ expect(job.completedAt).toBeInstanceOf(Date)+ },+ )++ it('does not expose credential-bearing database errors', async () => {+ const marker = 'bxsc_private-marker'+ const error = Object.assign(new Error(`database error ${marker}`), { parameters: [marker] })+ const service = new JobService({ insert: jest.fn().mockRejectedValue(error) } as any, {} as any, {} as any)+ const log = jest.spyOn(Logger.prototype, 'error').mockImplementation()+ try {+ let failure: unknown+ try {+ await service.createJob(null, JobType.CREATE_BOX, 'runner', ResourceType.BOX, 'box', {+ secretCredential: { token: marker },+ })+ } catch (caught) {+ failure = caught+ }+ expect(failure).toBeDefined()+ expect(String(failure)).not.toContain(marker)+ expect(JSON.stringify(log.mock.calls)).not.toContain(marker)+ } finally {+ log.mockRestore()+ }+ })++ it.each([JobStatus.COMPLETED, JobStatus.FAILED])('removes credentials in the %s transaction', async (status) => {+ const job = new Job({+ type: JobType.CREATE_BOX,+ runnerId: 'runner',+ resourceType: ResourceType.BOX,+ resourceId: 'box',+ status: JobStatus.IN_PROGRESS,+ payload: JSON.stringify({ image: 'base', secretCredential: { token: 'private' } }),+ })+ const manager = {+ findOne: jest.fn().mockResolvedValue(job),+ save: jest.fn().mockImplementation(async (_type, saved) => saved),+ }+ const handler = { handleJobCompletion: jest.fn().mockResolvedValue(undefined) }+ const service = new JobService(+ { manager: { transaction: (run: any) => run(manager) } } as any,+ {} as any,+ handler as any,+ )+ await service.updateJobStatus(job.id, status)+ expect(manager.save.mock.calls[0][1].getPayload()).toEqual({ image: 'base' })+ expect(job.completedAt).toBeInstanceOf(Date)+ })+})diff --git a/apps/api/src/box/services/job.service.ts b/apps/api/src/box/services/job.service.tsindex df8140e86..97fb4f298 100644--- a/apps/api/src/box/services/job.service.ts+++ b/apps/api/src/box/services/job.service.ts@@ -4,7 +4,7 @@* SPDX-License-Identifier: AGPL-3.0*/-import { ConflictException, Injectable, Logger, NotFoundException } from '@nestjs/common'+import { ConflictException, Injectable, Logger, NotFoundException, ServiceUnavailableException } from '@nestjs/common'import { JobConflictError } from '../errors/job-conflict.error'import { InjectRepository } from '@nestjs/typeorm'import { Repository, LessThan, In, EntityManager } from 'typeorm'@@ -36,7 +36,8 @@ export class JobService {/*** Create a job within the provided transaction manager- * If manager is null, uses the default repository (for non-transactional operations)+ * With a manager, the transaction owner must call notifyRunner after commit.+ * With null, insertion commits before this method notifies the runner.* @template T The JobType enum value - ensures compile-time type safety for resourceType and payload*/async createJob<T extends JobType>(@@ -73,9 +74,7 @@ export class JobService {this.logger.debug(`Created job ${job.id} of type ${type} for ${contextInfo} on runner ${runnerId}`)- // Notify runner via Redis - happens outside transaction- // If transaction rolls back, notification is harmless (runner will poll and find nothing)- await this.notifyRunner(runnerId, job.id)+ if (!manager) await this.notifyRunner(runnerId, job.id)return job} catch (error) {@@ -88,12 +87,17 @@ export class JobService {}throw new JobConflictError()}+ if (type === JobType.CREATE_BOX) {+ this.logger.error(`Could not create job for box ${resourceId} on runner ${runnerId}`)+ throw new ServiceUnavailableException('Could not create box job')+ }this.logger.error(`Error creating job: ${error}`)throw error}}- private async notifyRunner(runnerId: string, jobId: string): Promise<void> {+ /** Best-effort wake-up for a committed job; polling recovers missed notifications. */+ async notifyRunner(runnerId: string, jobId: string): Promise<void> {try {await this.redis.lpush(runnerJobQueueKey(runnerId), jobId)this.logger.debug(`Notified runner ${runnerId} about job ${jobId} via Redis`)@@ -251,6 +255,13 @@ export class JobService {if (status === JobStatus.COMPLETED || status === JobStatus.FAILED) {job.completedAt = new Date()+ if (job.type === JobType.CREATE_BOX) {+ const payload = job.getPayload()+ if (payload?.secretCredential) {+ delete payload.secretCredential+ job.payload = JSON.stringify(payload)+ }+ }}if (resultMetadata) {diff --git a/apps/api/src/box/services/memory-mib.spec.ts b/apps/api/src/box/services/memory-mib.spec.tsindex 868efb9a3..4ee9285e0 100644--- a/apps/api/src/box/services/memory-mib.spec.ts+++ b/apps/api/src/box/services/memory-mib.spec.ts@@ -82,6 +82,7 @@ describe('Cloud MiB allocation regression', () => {it('passes exact GiB to V0 create and recovery', async () => {const adapter = new RunnerAdapterV0()+ Object.assign(adapter, { config: { get: () => false } })const create = jest.fn().mockResolvedValue({ data: {} })const recover = jest.fn().mockResolvedValue(undefined)Object.assign(adapter, { boxApiClient: { create, recover } })@@ -95,6 +96,7 @@ describe('Cloud MiB allocation regression', () => {it('passes exact GiB to V2 create jobs', async () => {const createJob = jest.fn().mockResolvedValue(undefined)const adapter = new RunnerAdapterV2({} as never, {} as never, { createJob } as never)+ Object.assign(adapter, { config: { get: () => false } })await adapter.init({ id: 'runner-memory' } as never)await adapter.createBox(Object.assign(new Box('us'), { mem: 1, memoryMib: 300 }), 'alpine:latest')expect(createJob.mock.calls[0][5].memoryQuota).toBe(300 / 1024)diff --git a/apps/api/src/box/services/secret-credential.integration.spec.ts b/apps/api/src/box/services/secret-credential.integration.spec.tsnew file mode 100644index 000000000..a46702e4d--- /dev/null+++ b/apps/api/src/box/services/secret-credential.integration.spec.ts@@ -0,0 +1,181 @@+import { Logger } from '@nestjs/common'+import { Test } from '@nestjs/testing'+import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'+import { createHash, randomUUID } from 'node:crypto'+import { DataSource } from 'typeorm'+import { AddSecretCredential1794873600000 } from '../../migrations/pre-deploy/1794873600000-add-secret-credential-migration'+import { SecretCredentialController, SECRET_CREDENTIAL_PATH } from '../controllers/secret-credential.controller'+import { SecretCredentialService } from './secret-credential.service'+import { RunnerAdapterV2 } from '../runner-adapter/runnerAdapter.v2'++const describeDatabase = process.env.DB_HOST ? describe : describe.skip++describeDatabase('Secret credentials with real PostgreSQL and HTTP', () => {+ let db: DataSource+ let service: SecretCredentialService+ let app: any+ const request = (_server: unknown) => ({+ post: (path: string) => ({+ send: async (body: unknown) => {+ const response = await fetch((await app.getUrl()) + path, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ })+ return {+ status: response.status,+ headers: { 'cache-control': response.headers.get('cache-control') },+ body: await response.json(),+ }+ },+ }),+ })+ const schema = `credential_${randomUUID().replaceAll('-', '')}`+ const binding = {+ runnerId: 'runner-1',+ boxId: 'box-1',+ organizationId: randomUUID(),+ secretIds: [randomUUID(), randomUUID()],+ }++ beforeAll(async () => {+ db = await new DataSource({+ type: 'postgres',+ host: process.env.DB_HOST,+ port: Number(process.env.DB_PORT || 5432),+ username: process.env.DB_USERNAME,+ password: process.env.DB_PASSWORD,+ database: process.env.DB_DATABASE,+ extra: { options: `-c search_path=${schema}` },+ }).initialize()+ await db.query(`CREATE SCHEMA "${schema}"`)+ await db.query(+ 'CREATE TABLE box (id varchar(64) PRIMARY KEY, "runnerId" text, "organizationId" uuid, "desiredState" text, state text)',+ )+ const runner = db.createQueryRunner()+ try {+ await new AddSecretCredential1794873600000().up(runner)+ } finally {+ await runner.release()+ }+ service = new SecretCredentialService(db)+ const module = await Test.createTestingModule({+ controllers: [SecretCredentialController],+ providers: [{ provide: SecretCredentialService, useValue: service }],+ }).compile()+ app = module.createNestApplication()+ app.setGlobalPrefix('api', { exclude: [SECRET_CREDENTIAL_PATH] })+ await app.listen(0, '127.0.0.1')+ })++ beforeEach(async () => {+ await db.query('TRUNCATE box CASCADE')+ await db.query("INSERT INTO box VALUES ($1, $2, $3, 'started', 'starting')", [+ binding.boxId,+ binding.runnerId,+ binding.organizationId,+ ])+ })++ afterAll(async () => {+ await app?.close()+ if (db?.isInitialized) {+ await db.query(`DROP SCHEMA "${schema}" CASCADE`)+ await db.destroy()+ }+ })++ it('issues from v2 refs with only hash stored and consumes exactly once over HTTP', async () => {+ const jobs = {+ createJob: jest.fn().mockResolvedValue({ id: 'job', runnerId: binding.runnerId }),+ notifyRunner: jest.fn(),+ }+ const adapter = new RunnerAdapterV2({} as any, { manager: db.manager } as any, jobs as any)+ Object.assign(adapter, { config: { get: () => true }, credentials: service })+ await adapter.init({ id: binding.runnerId } as any)+ await adapter.createBox(+ {+ id: binding.boxId,+ organizationId: binding.organizationId,+ secrets: binding.secretIds.map((secretId, i) => ({+ secretId,+ name: `secret-${i}`,+ value: 'must-not-leak',+ hosts: ['example.com'],+ headers: { authorization: '{value}' },+ })),+ } as any,+ 'base',+ )+ const payload = jobs.createJob.mock.calls[0][5]+ expect(JSON.stringify(payload)).not.toContain('must-not-leak')+ expect(payload.secrets[0]).not.toHaveProperty('value')+ const { token, expiresAt } = payload.secretCredential+ expect(token).toMatch(/^bxsc_[A-Za-z0-9_-]{43}$/)+ const [row] = await db.query('SELECT * FROM secret_credential')+ expect(row.token_hash).toEqual(createHash('sha256').update(token).digest())+ expect(JSON.stringify(row)).not.toContain(token)+ expect(row.expires_at.getTime() - row.issued_at.getTime()).toBe(900_000)+ expect(row.expires_at.toISOString()).toBe(expiresAt)+ const invoke = (runner_id = binding.runnerId) =>+ request(app.getHttpServer())+ .post('/' + SECRET_CREDENTIAL_PATH)+ .send({ token, runner_id })+ expect((await invoke('wrong-runner')).body).toEqual({ active: false })+ const result = await invoke()+ expect(result.status).toBe(200)+ expect(result.headers['cache-control']).toBe('no-store')+ expect(result.body).toEqual({+ active: true,+ credential_id: row.id,+ runner_id: binding.runnerId,+ box_id: binding.boxId,+ organization_id: binding.organizationId,+ grants: binding.secretIds.map((secret_id) => ({ secret_id })),+ expires_at: expiresAt,+ })+ const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation()+ try {+ expect((await invoke()).body).toEqual({ active: false })+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(row.id))+ expect(JSON.stringify(warn.mock.calls)).not.toContain(token)+ } finally {+ warn.mockRestore()+ }+ })++ it('allows only one concurrent consumer across connections', async () => {+ const { token } = await service.issue(binding)+ const responses = await Promise.all(Array.from({ length: 8 }, () => service.consume(token, binding.runnerId)))+ expect(responses.filter((r) => r.active)).toHaveLength(1)+ expect(responses.filter((r) => !r.active)).toEqual(Array(7).fill({ active: false }))+ })++ it('rejects expiry at the boundary and deleted boxes', async () => {+ const expired = await service.issue(binding)+ await db.query("UPDATE secret_credential SET issued_at = now() - interval '15 minutes', expires_at = now()")+ expect(await service.consume(expired.token, binding.runnerId)).toEqual({ active: false })+ const deleted = await service.issue(binding)+ await db.query('DELETE FROM box WHERE id = $1', [binding.boxId])+ expect(await service.consume(deleted.token, binding.runnerId)).toEqual({ active: false })+ expect(await db.query('SELECT * FROM secret_credential')).toEqual([])+ })++ it('keeps malformed and unknown tokens inactive and hides the route from OpenAPI', async () => {+ for (const token of [null, {}, '', 'bxsc_' + 'a'.repeat(43)]) {+ const result = await request(app.getHttpServer())+ .post('/' + SECRET_CREDENTIAL_PATH)+ .send({ token, runner_id: binding.runnerId })+ expect(result.status).toBe(200)+ expect(result.body).toEqual({ active: false })+ }+ expect(+ (+ await request(app.getHttpServer())+ .post('/api/' + SECRET_CREDENTIAL_PATH)+ .send({})+ ).status,+ ).toBe(404)+ expect(SwaggerModule.createDocument(app, new DocumentBuilder().build()).paths).toEqual({})+ })+})diff --git a/apps/api/src/box/services/secret-credential.service.spec.ts b/apps/api/src/box/services/secret-credential.service.spec.tsnew file mode 100644index 000000000..b51320fbd--- /dev/null+++ b/apps/api/src/box/services/secret-credential.service.spec.ts@@ -0,0 +1,34 @@+import { Logger, ServiceUnavailableException } from '@nestjs/common'+import { SecretCredentialService } from './secret-credential.service'++describe('Secret credential database failures', () => {+ const binding = { runnerId: 'runner', boxId: 'box', organizationId: 'org', secretIds: ['secret-id'] }++ it.each(['issue', 'consume', 'replay lookup'])('sanitizes failures during %s', async (operation) => {+ const privateDetail = 'private-driver-parameters'+ const driverError = Object.assign(new Error(privateDetail), { parameters: [privateDetail] })+ const query = jest.fn().mockRejectedValue(driverError)+ if (operation === 'replay lookup') query.mockResolvedValueOnce([[]])+ const service = new SecretCredentialService({ query, transaction: (fn: any) => fn({ query }) } as any)+ const log = jest.spyOn(Logger.prototype, 'error').mockImplementation()+ const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation()+ try {+ const result =+ operation === 'issue' ? service.issue(binding) : service.consume(`bxsc_${'a'.repeat(43)}`, binding.runnerId)+ const error = await result.catch((caught) => caught)+ expect(error).toBeInstanceOf(ServiceUnavailableException)+ expect(error.getStatus()).toBe(503)+ expect(error.message).toBe(+ operation === 'issue' ? 'Could not issue secret credential' : 'Could not consume secret credential',+ )+ expect(error.cause).toBeUndefined()+ expect(JSON.stringify(error)).not.toContain(privateDetail)+ expect(log).not.toHaveBeenCalled()+ expect(warn).not.toHaveBeenCalled()+ expect(query).toHaveBeenCalledTimes(operation === 'replay lookup' ? 2 : 1)+ } finally {+ log.mockRestore()+ warn.mockRestore()+ }+ })+})diff --git a/apps/api/src/box/services/secret-credential.service.ts b/apps/api/src/box/services/secret-credential.service.tsnew file mode 100644index 000000000..ec6bb6b19--- /dev/null+++ b/apps/api/src/box/services/secret-credential.service.ts@@ -0,0 +1,85 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */++import { Injectable, Logger, ServiceUnavailableException } from '@nestjs/common'+import { createHash, randomBytes } from 'node:crypto'+import { DataSource, EntityManager } from 'typeorm'++type CredentialGrant = { secret_id: string }+type ActiveCredential = {+ active: true+ credential_id: string+ runner_id: string+ box_id: string+ organization_id: string+ grants: CredentialGrant[]+ expires_at: Date+}++@Injectable()+export class SecretCredentialService {+ private readonly logger = new Logger(SecretCredentialService.name)++ constructor(private readonly database: DataSource) {}++ async issue(+ binding: { runnerId: string; boxId: string; organizationId: string; secretIds: string[] },+ manager?: EntityManager,+ ): Promise<{ token: string; expiresAt: string }> {+ if (!manager) return this.database.transaction((transaction) => this.issue(binding, transaction))+ const token = `bxsc_${randomBytes(32).toString('base64url')}`+ const grants = binding.secretIds.map((secret_id) => ({ secret_id }))+ try {+ // Serialize issuance with logical deletion, which locks Box before revoking credentials.+ const [box] = await manager.query(+ `SELECT id FROM box WHERE id = $1 AND "runnerId" = $2 AND "organizationId" = $3+ AND "desiredState" <> 'destroyed' AND state <> 'destroyed' FOR UPDATE`,+ [binding.boxId, binding.runnerId, binding.organizationId],+ )+ if (!box) throw new Error('Box is not eligible for a secret credential')+ const [row] = await manager.query(+ `INSERT INTO secret_credential (token_hash, runner_id, box_id, organization_id, grants, expires_at)+ VALUES ($1, $2, $3, $4, $5, now() + interval '15 minutes') RETURNING expires_at`,+ [this.hash(token), binding.runnerId, binding.boxId, binding.organizationId, JSON.stringify(grants)],+ )+ return { token, expiresAt: row.expires_at.toISOString() }+ } catch {+ // Driver errors can include bound parameters; never propagate grants or hashes to logging interceptors.+ throw new ServiceUnavailableException('Could not issue secret credential')+ }+ }++ async consume(token: unknown, runnerId: unknown): Promise<ActiveCredential | { active: false }> {+ if (+ typeof token !== 'string' ||+ !/^bxsc_[A-Za-z0-9_-]{43}$/.test(token) ||+ typeof runnerId !== 'string' ||+ runnerId.length === 0 ||+ runnerId.length > 64+ ) {+ return { active: false }+ }+ const hash = this.hash(token)+ try {+ // PostgreSQL rechecks the predicates after waiting for a competing consumer's row lock.+ const [rows] = await this.database.query(+ `UPDATE secret_credential SET used_at = now()+ WHERE token_hash = $1 AND runner_id = $2 AND used_at IS NULL AND expires_at > now()+ RETURNING id AS credential_id, runner_id, box_id, organization_id, grants, expires_at`,+ [hash, runnerId],+ )+ if (rows.length) return { active: true, ...rows[0] }+ const [used] = await this.database.query(+ 'SELECT id FROM secret_credential WHERE token_hash = $1 AND used_at IS NOT NULL',+ [hash],+ )+ if (used) this.logger.warn(`Secret credential replay: credential_id=${used.id}`)+ return { active: false }+ } catch {+ throw new ServiceUnavailableException('Could not consume secret credential')+ }+ }++ private hash(token: string): Buffer {+ return createHash('sha256').update(token).digest()+ }+}diff --git a/apps/api/src/box/services/secret-server-client.spec.ts b/apps/api/src/box/services/secret-server-client.spec.tsindex cf3f65c1d..0ebb7c1f5 100644--- a/apps/api/src/box/services/secret-server-client.spec.ts+++ b/apps/api/src/box/services/secret-server-client.spec.ts@@ -318,6 +318,16 @@ describe('SecretServerClient HTTP boundary', () => {expect(requests).toHaveLength(0)})+ it('refuses identity headers without authorization before POST', async () => {+ jest.spyOn(GoogleAuth.prototype, 'getIdTokenClient').mockResolvedValue({+ getRequestHeaders: async () => new Headers(),+ } as any)+ await expect(+ client(url, { 'secretServer.devToken': undefined }).storeBoxSecrets('id', 'org', 'user', secrets),+ ).rejects.toMatchObject({ status: 503, message: 'Secret store unavailable' })+ expect(requests).toHaveLength(0)+ })+it('times out identity acquisition and never posts after a late completion', async () => {jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] })let release: (value: any) => voiddiff --git a/apps/api/src/ci/ci-native-workers.spec.ts b/apps/api/src/ci/ci-native-workers.spec.tsindex 75db10add..da3b5edc0 100644--- a/apps/api/src/ci/ci-native-workers.spec.ts+++ b/apps/api/src/ci/ci-native-workers.spec.ts@@ -31,6 +31,7 @@ import { ImageAdmissionService } from '../image/services/image-admission.serviceimport { BoxState } from '../box/enums/box-state.enum'import { BoxDesiredState } from '../box/enums/box-desired-state.enum'import { CustomNamingStrategy } from '../common/utils/naming-strategy.util'+import { AddSecretCredential1794873600000 } from '../migrations/pre-deploy/1794873600000-add-secret-credential-migration'import { AddCiListenerState1793700000000 } from '../migrations/pre-deploy/1793700000000-add-ci-listener-state-migration'const integration = process.env.DB_HOST ? describe : describe.skip@@ -97,6 +98,7 @@ integration('CI native workers (shared lease, actual PostgreSQL and HTTP)', () =const query = db.createQueryRunner()try {await new AddCiListenerState1793700000000().up(query)+ await new AddSecretCredential1794873600000().up(query)} finally {await query.release()}@@ -171,7 +173,7 @@ integration('CI native workers (shared lease, actual PostgreSQL and HTTP)', () =})beforeEach(async () => {await db.query(- 'TRUNCATE ci_listener_state,ci_installation_binding,"user",organization_user,box,box_last_activity,box_checkpoint_state',+ 'TRUNCATE ci_listener_state,ci_installation_binding,"user",organization_user,box,box_last_activity,box_checkpoint_state,secret_credential',)await db.query(`INSERT INTO ci_installation_binding VALUES($1,1,'github.com',$2,10,20,'owner','User',$3,$4,true,true,'ready')`,diff --git a/apps/api/src/main.spec.ts b/apps/api/src/main.spec.tsindex c524bacdc..40d4ed5d2 100644--- a/apps/api/src/main.spec.ts+++ b/apps/api/src/main.spec.ts@@ -39,6 +39,9 @@ jest.mock('./common/utils/app-mode', () => ({jest.mock('./boxlite-rest/boxlite-ws-proxy.service', () => ({ BoxliteWsProxyService: class {} }))jest.mock('./mcp/mcp.controller', () => ({ mcpStrategy: {} }))jest.mock('./mcp/mcp-auth-metadata', () => ({ MCP_ROOT_ROUTES: [] }))+jest.mock('./box/controllers/secret-credential.controller', () => ({+ SECRET_CREDENTIAL_PATH: 'internal/v1/credentials/introspect',+}))jest.mock('./mcp/mcp-body', () => ({ useApiBodyParsers: jest.fn() }))jest.mock('./mcp/mcp-tools', () => ({ McpTools: class {} }))jest.mock('./mcp/mcp-routes', () => ({ servedOperations: () => [] }))@@ -96,6 +99,9 @@ describe('API bootstrap listener', () => {require('./main')await new Promise<void>((resolve) => setImmediate(resolve))expect(listen).toHaveBeenCalledWith(3300, host || '0.0.0.0')+ expect(app.setGlobalPrefix).toHaveBeenCalledWith('api', {+ exclude: ['internal/v1/credentials/introspect'],+ })expect(httpServer.requestTimeout).toBe(0)expect(service.start).toHaveBeenCalledTimes(1)expect(listen.mock.invocationCallOrder[0]).toBeLessThan(service.start.mock.invocationCallOrder[0])diff --git a/apps/api/src/main.ts b/apps/api/src/main.tsindex 379ee983d..64eebbd8d 100644--- a/apps/api/src/main.ts+++ b/apps/api/src/main.ts@@ -5,6 +5,7 @@*/import { otelSdk } from './tracing'+import { SECRET_CREDENTIAL_PATH } from './box/controllers/secret-credential.controller'import { installCiWebhookBodyParser } from './ci/ci-webhook-body'import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'import { NestFactory } from '@nestjs/core'@@ -141,7 +142,7 @@ async function bootstrap() {}const globalPrefix = 'api'- app.setGlobalPrefix(globalPrefix, { exclude: MCP_ROOT_ROUTES })+ app.setGlobalPrefix(globalPrefix, { exclude: [...MCP_ROOT_ROUTES, SECRET_CREDENTIAL_PATH] })// Built once: the Swagger UI serves it, and the MCP catalog reads the dashboard routes from it.const document = SwaggerModule.createDocument(app, getOpenApiConfig(configService.get('oidc.issuer')))diff --git a/apps/api/src/migrations/pre-deploy/1794873600000-add-secret-credential-migration.ts b/apps/api/src/migrations/pre-deploy/1794873600000-add-secret-credential-migration.tsnew file mode 100644index 000000000..f394dee33--- /dev/null+++ b/apps/api/src/migrations/pre-deploy/1794873600000-add-secret-credential-migration.ts@@ -0,0 +1,24 @@+import { MigrationInterface, QueryRunner } from 'typeorm'++export class AddSecretCredential1794873600000 implements MigrationInterface {+ async up(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`CREATE TABLE secret_credential (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ token_hash bytea NOT NULL UNIQUE,+ runner_id varchar(64) NOT NULL,+ box_id varchar(64) NOT NULL REFERENCES box(id) ON DELETE CASCADE,+ organization_id uuid NOT NULL,+ grants jsonb NOT NULL,+ issued_at timestamptz NOT NULL DEFAULT now(),+ expires_at timestamptz NOT NULL,+ used_at timestamptz,+ CHECK (expires_at > issued_at)+ )`)+ await queryRunner.query('CREATE INDEX secret_credential_box_idx ON secret_credential(box_id)')+ await queryRunner.query('CREATE INDEX secret_credential_expires_idx ON secret_credential(expires_at)')+ }++ async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query('DROP TABLE secret_credential')+ }+}diff --git a/apps/infra/bootstrap/aws.test.ts b/apps/infra/bootstrap/aws.test.tsindex 1e65c3703..e7333bddd 100644--- a/apps/infra/bootstrap/aws.test.ts+++ b/apps/infra/bootstrap/aws.test.ts@@ -130,3 +130,44 @@ test('a failing AWS call surfaces the CLI stderr rather than a generic failure',}await assert.rejects(invoke(run), (error: any) => error instanceof AwsBootstrapError && /AccessDenied: nope/.test(error.message))})++test('AWS bootstrap reconciles stage-scoped credential ACL permissions', async () => {+ let policy: any+ await bootstrapAws({+ repo: 'boxlite-ai/boxlite',+ stage: 'dev',+ accountId: '123456789012',+ region: 'us-west-2',+ log: () => {},+ run: async (_command, args) => {+ if (args[0] === 'iam' && args[1] === 'put-role-policy') {+ policy = JSON.parse(args[args.indexOf('--policy-document') + 1])+ }+ return { code: 0, stdout: args[1] === 'list-policy-versions' ? '{"Versions":[]}' : '{}', stderr: '' }+ },+ })+ for (const action of [+ 'CreateWebACL',+ 'GetWebACL',+ 'UpdateWebACL',+ 'DeleteWebACL',+ 'AssociateWebACL',+ 'GetWebACLForResource',+ 'ListResourcesForWebACL',+ 'ListTagsForResource',+ 'TagResource',+ 'UntagResource',+ ]) {+ const statements = policy.Statement.filter(+ (s: any) => s.Effect === 'Allow' && ([] as string[]).concat(s.Action).includes(`wafv2:${action}`),+ )+ assert.ok(statements.length, `missing wafv2:${action}`)+ assert.deepEqual(+ statements.flatMap((s: any) => s.Resource),+ ['arn:aws:wafv2:us-west-2:123456789012:regional/webacl/boxlite-dev-internal-routes/*'],+ )+ }+ const detach = policy.Statement.find((s: any) => s.Action === 'wafv2:DisassociateWebACL')+ assert.equal(detach.Resource, '*')+ assert.deepEqual(detach.Condition, { StringEquals: { 'aws:RequestedRegion': 'us-west-2' } })+})diff --git a/apps/infra/bootstrap/aws/README.md b/apps/infra/bootstrap/aws/README.mdindex 79f0ad84f..eddeec03f 100644--- a/apps/infra/bootstrap/aws/README.md+++ b/apps/infra/bootstrap/aws/README.md@@ -59,6 +59,25 @@ SSM instance targets and SES identity management. [Security](../../docs/aws/securecords those limits. `cloudfront-keyvaluestore:*` is separate from `cloudfront:*`; the latter'swildcard does not cover another service prefix.+Credential ingress uses the regional ACL `boxlite-<stage>-internal-routes`.+The deploy policy scopes WAF creation, lifecycle, tagging and association to that+ACL in the stage account and region. Disassociation currently uses a wildcard+resource with a requested-region condition. Together with the existing ELB grant,+this permits detaching an ACL from unrelated ALBs in that region.++The [WAF V2 authorization table](https://docs.aws.amazon.com/service-authorization/latest/reference/list_wafv2.html#awswafv2-DisassociateWebACL)+supports ALB resources for disassociation, not web ACL resources. A supported+restriction uses the actual deployed ALB ARN; it cannot select the attached ACL+by its name. Bootstrap must obtain that ARN from trusted stage inventory before+using such a restriction. SST's generated ALB names can truncate the stage, so+an assumed `boxlite-<stage>-*` name is not a safe substitute. Renaming an existing+ALB would require a separate replacement rollout. The+[AWS permissions guide](https://docs.aws.amazon.com/waf/latest/developerguide/security_iam_service-with-iam.html)+also describes the separate ELB permission required by the disassociation operation.++Reconcile bootstrap and read back its inline deploy policy before previewing or+applying either AWS deployment path. Updating the repository does not update a live role.+## Artifact retention and changesBootstrap creates missing ECR/artifact stores but does not delete or replace them. Its bucketdiff --git a/apps/infra/bootstrap/aws/deploy-role-policy.json b/apps/infra/bootstrap/aws/deploy-role-policy.jsonindex 43322f4a2..5d1a40246 100644--- a/apps/infra/bootstrap/aws/deploy-role-policy.json+++ b/apps/infra/bootstrap/aws/deploy-role-policy.json@@ -1,6 +1,30 @@{"Version": "2012-10-17","Statement": [+ {+ "Sid": "CredentialIngressAclForThisStage",+ "Effect": "Allow",+ "Action": [+ "wafv2:CreateWebACL",+ "wafv2:GetWebACL",+ "wafv2:UpdateWebACL",+ "wafv2:DeleteWebACL",+ "wafv2:AssociateWebACL",+ "wafv2:GetWebACLForResource",+ "wafv2:ListResourcesForWebACL",+ "wafv2:ListTagsForResource",+ "wafv2:TagResource",+ "wafv2:UntagResource"+ ],+ "Resource": "arn:aws:wafv2:<REGION>:<ACCOUNT>:regional/webacl/boxlite-<STAGE>-internal-routes/*"+ },+ {+ "Sid": "DisassociateCredentialIngressInThisRegion",+ "Effect": "Allow",+ "Action": "wafv2:DisassociateWebACL",+ "Resource": "*",+ "Condition": { "StringEquals": { "aws:RequestedRegion": "<REGION>" } }+ },{"Sid": "BoxLiteAwsControlPlane","Effect": "Allow",diff --git a/apps/infra/deployment/release-safety.test.ts b/apps/infra/deployment/release-safety.test.tsindex c82d46069..4ad40cea6 100644--- a/apps/infra/deployment/release-safety.test.ts+++ b/apps/infra/deployment/release-safety.test.ts@@ -659,6 +659,10 @@ test('the grants that are NOT stage-scoped are the documented ones, and only tho* appear without failing anything.*/const WILDCARD_RESOURCE_STATEMENTS: Array<[string, string]> = [+ [+ 'DisassociateCredentialIngressInThisRegion',+ 'WAF disassociation requires *; exact action and region are pinned below',+ ],['BoxLiteAwsControlPlane', 'the control-plane calls SST makes have no resource-level ARNs'],['RunnerCommandStatus', 'SSM command-history APIs are list-shaped and take no resource'],['ReadIamAndAccountMetadata', 'account and IAM reads SST performs before it knows any resource'],@@ -679,6 +683,14 @@ test('the grants that are NOT stage-scoped are the documented ones, and only tho*/const RESOURCELESS_SECRETSMANAGER = ['secretsmanager:ListSecrets', 'secretsmanager:GetRandomPassword']+ assert.deepEqual(findStatement(statements, 'DisassociateCredentialIngressInThisRegion'), {+ Sid: 'DisassociateCredentialIngressInThisRegion',+ Effect: 'Allow',+ Action: 'wafv2:DisassociateWebACL',+ Resource: '*',+ Condition: { StringEquals: { 'aws:RequestedRegion': '<REGION>' } },+ })+for (const [sid] of WILDCARD_RESOURCE_STATEMENTS) {const statement = statements.find((candidate: any) => candidate.Sid === sid)assert.ok(statement, `${sid} is allowed a wildcard resource but no longer exists`)diff --git a/apps/infra/mdeploy/package.json b/apps/infra/mdeploy/package.jsonindex 72cd85db0..a998fb91a 100644--- a/apps/infra/mdeploy/package.json+++ b/apps/infra/mdeploy/package.json@@ -8,6 +8,7 @@"mdeploy": "bin/mdeploy.ts"},"exports": {+ "./internal-route-policy": "./stack/providers/aws/internal-route-policy.ts","./hosts": "./stack/hosts.ts","./runner-binary": "./stack/runner-binary.ts","./runner-kernel": "./stack/runner-kernel.ts",diff --git a/apps/infra/mdeploy/stack/providers/aws/api.ts b/apps/infra/mdeploy/stack/providers/aws/api.tsindex b190f04f7..fd9608c6a 100644--- a/apps/infra/mdeploy/stack/providers/aws/api.ts+++ b/apps/infra/mdeploy/stack/providers/aws/api.ts@@ -22,6 +22,7 @@import type { Api, ApiCapability, ApiDependencies, ApiProvider, ApiRequest } from '../../api.ts'import { publicHostsFor } from '../../api.ts'+import { denyPublicInternalRoutes } from './internal-route-policy.ts'import { CACHE_PASSWORD_VARIABLE } from '../../cache.ts'import { CLICKHOUSE_PASSWORD_VARIABLE } from '../../clickhouse.ts'import type { WorkloadHost } from '../../cluster.ts'@@ -192,6 +193,7 @@ export const awsApiProvider =* cycle: the API's environment could carry the name before the role was* real.*/+ denyPublicInternalRoutes(service.nodes.loadBalancer.arn)const vending = new aws.iam.Role('S3AccessRole', {name: storage.credentialVending.roleName,assumeRolePolicy: service.nodes.taskRole.arn.apply((taskRoleArn: string) =>diff --git a/apps/infra/mdeploy/stack/providers/aws/internal-route-policy.ts b/apps/infra/mdeploy/stack/providers/aws/internal-route-policy.tsnew file mode 100644index 000000000..f16e2e809--- /dev/null+++ b/apps/infra/mdeploy/stack/providers/aws/internal-route-policy.ts@@ -0,0 +1,36 @@+/** Public API and dashboard origin traffic must not reach unauthenticated internal routes. */+export function denyPublicInternalRoutes(albArn: $util.Input<string>): void {+ const acl = new aws.wafv2.WebAcl('ApiInternalRoutePolicy', {+ name: `boxlite-${$app.stage}-internal-routes`,+ scope: 'REGIONAL',+ defaultAction: { allow: {} },+ visibilityConfig: {+ cloudwatchMetricsEnabled: true,+ metricName: 'ApiInternalRoutes',+ sampledRequestsEnabled: false,+ },+ rules: [+ {+ name: 'DenyInternalRoutes',+ priority: 0,+ action: { block: {} },+ statement: {+ regexMatchStatement: {+ fieldToMatch: { uriPath: {} },+ regexString: '^(?:/api)?/internal(?:/|$)',+ textTransformations: [+ { priority: 0, type: 'URL_DECODE' },+ { priority: 1, type: 'LOWERCASE' },+ ],+ },+ },+ visibilityConfig: {+ cloudwatchMetricsEnabled: true,+ metricName: 'DenyInternalRoutes',+ sampledRequestsEnabled: false,+ },+ },+ ],+ })+ new aws.wafv2.WebAclAssociation('ApiInternalRoutePolicyAssociation', { resourceArn: albArn, webAclArn: acl.arn })+}diff --git a/apps/infra/mdeploy/stack/providers/gcp/api.ts b/apps/infra/mdeploy/stack/providers/gcp/api.tsindex cd5175894..17fb064b4 100644--- a/apps/infra/mdeploy/stack/providers/gcp/api.ts+++ b/apps/infra/mdeploy/stack/providers/gcp/api.ts@@ -643,7 +643,28 @@ export const gcpApiProvider =networkEndpointType: 'SERVERLESS',cloudRun: { service: service.name },})+ const internalRoutePolicy = new gcp.compute.SecurityPolicy('ApiInternalRoutePolicy', {+ project,+ rules: [+ {+ priority: 100,+ action: 'deny(403)',+ match: {+ expr: { expression: "request.path.urlDecode().lower().matches('^(?:/api)?/internal(?:/|$)')" },+ },+ },+ {+ priority: 2147483647,+ action: 'allow',+ match: {+ versionedExpr: 'SRC_IPS_V1',+ config: { srcIpRanges: ['*'] },+ },+ },+ ],+ })const backend = new gcp.compute.BackendService('ApiBackend', {+ securityPolicy: internalRoutePolicy.id,name: instanceFor({ app: $app.name, stage: $app.stage, artifact: 'api' }),project,loadBalancingScheme: 'EXTERNAL_MANAGED',@@ -824,7 +845,14 @@ export const gcpApiProvider ={name: API_PATH_MATCHER,defaultService: internalBackend.id,- routeRules: apiPrefixRouteRules(internalBackend.id),+ routeRules: [+ {+ priority: 0,+ matchRules: [{ fullPathMatch: '/internal/v1/credentials/introspect' }],+ service: internalBackend.id,+ },+ ...apiPrefixRouteRules(internalBackend.id),+ ],},],})diff --git a/apps/infra/mdeploy/test/gcp-checkpoint-api.test.ts b/apps/infra/mdeploy/test/gcp-checkpoint-api.test.tsindex 24a132208..2f5043e72 100644--- a/apps/infra/mdeploy/test/gcp-checkpoint-api.test.ts+++ b/apps/infra/mdeploy/test/gcp-checkpoint-api.test.ts@@ -41,6 +41,7 @@ for (const checkpointAccess of [false, true]) {certificatemanager: ['DnsAuthorization', 'Certificate'],dns: ['ManagedZone', 'RecordSet'],compute: [+ 'SecurityPolicy','RegionNetworkEndpointGroup','BackendService','URLMap',diff --git a/apps/infra/mdeploy/test/internal-route-policy.test.ts b/apps/infra/mdeploy/test/internal-route-policy.test.tsnew file mode 100644index 000000000..3e0766a94--- /dev/null+++ b/apps/infra/mdeploy/test/internal-route-policy.test.ts@@ -0,0 +1,143 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import test from 'node:test'+import { output } from '@pulumi/pulumi'+import { awsApiProvider } from '../stack/providers/aws/api.ts'+import { denyPublicInternalRoutes } from '../stack/providers/aws/internal-route-policy.ts'++test('AWS API synthesis attaches the deny policy to the service ALB', () => {+ const globals = globalThis as any+ const previous = { aws: globals.aws, sst: globals.sst, $app: globals.$app }+ const resources = new Map<string, any>()+ class Resource {+ arn = output('generated-acl-arn')+ name = output('resource-name')+ constructor(name: string, args: any) {+ resources.set(name, args)+ }+ }+ const albArn = output('arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/actual-api/123')+ class Service {+ url = output('https://api.example.com/')+ nodes = {+ loadBalancer: { arn: albArn, arnSuffix: output('app/actual-api/123') },+ taskRole: { arn: output('task-role-arn'), name: output('task-role') },+ }+ }+ class Router {+ url = output('https://dashboard.example.com/')+ route() {}+ }+ try {+ globals.$app = { stage: 'dev' }+ globals.aws = {+ wafv2: { WebAcl: Resource, WebAclAssociation: Resource },+ iam: { Role: Resource, RolePolicy: Resource },+ }+ globals.sst = { aws: { Service, Router } }+ awsApiProvider({+ domain: 'example.com',+ dashboardDomain: null,+ dns: {} as any,+ dependencies: {+ host: { cloud: 'aws', cluster: {} },+ placement: { cloud: 'aws' },+ storage: {+ binding: { cloud: 'aws', bucketArn: output('bucket-arn'), credentialVending: { roleName: 'vending' } },+ },+ database: { binding: { passwordRef: output('db-password') } },+ cache: { binding: { passwordRef: output('cache-password') } },+ clickhouse: { active: false },+ waitFor: [],+ } as any,+ })({ domain: 'example.com', image: 'api-image', port: 3000, environment: {}, secrets: {}, capabilities: [] })+ const association = resources.get('ApiInternalRoutePolicyAssociation')+ assert.ok(association, 'the public service must have an ACL association')+ assert.equal(association.resourceArn, albArn)+ assert.ok(association.webAclArn)+ assert.deepEqual(resources.get('ApiInternalRoutePolicy').rules[0].action, { block: {} })+ } finally {+ Object.assign(globals, previous)+ }+})++test('AWS public ALB policy blocks decoded internal paths without sampling credentials', () => {+ const resources: { name: string; args: any }[] = []+ const previous = (globalThis as any).aws+ const previousApp = (globalThis as any).$app+ class Resource {+ arn = 'policy-arn'+ constructor(name: string, args: any) {+ resources.push({ name, args })+ }+ }+ try {+ ;(globalThis as any).aws = { wafv2: { WebAcl: Resource, WebAclAssociation: Resource } }+ ;(globalThis as any).$app = { stage: 'dev' }+ denyPublicInternalRoutes('public-alb')+ const policy = resources[0].args+ assert.equal(policy.scope, 'REGIONAL')+ assert.deepEqual(policy.defaultAction, { allow: {} })+ const rule = policy.rules[0]+ assert.deepEqual(rule.action, { block: {} })+ const match = rule.statement.regexMatchStatement+ assert.ok(match)+ assert.deepEqual(match.fieldToMatch, { uriPath: {} })+ assert.deepEqual(match.textTransformations, [+ { priority: 0, type: 'URL_DECODE' },+ { priority: 1, type: 'LOWERCASE' },+ ])+ for (const [path, denied] of [+ ['/internal/v1/credentials/introspect', true],+ ['/api/INTERNAL/v1/credentials/introspect', true],+ ['/api/%69nternal/v1/credentials/introspect', true],+ ['/internal', true],+ ['/api/internal', true],+ ['/api/v1/boxes/internal/start', false],+ ['/api/internal-box', false],+ ] as const) {+ const normalized = decodeURIComponent(path).toLowerCase()+ const blocked = new RegExp(match.regexString).test(normalized)+ assert.equal(blocked, denied, path)+ }+ assert.equal(policy.name, 'boxlite-dev-internal-routes')+ assert.equal(rule.visibilityConfig.sampledRequestsEnabled, false)+ assert.deepEqual(resources[1].args, { resourceArn: 'public-alb', webAclArn: 'policy-arn' })+ } finally {+ ;(globalThis as any).aws = previous+ ;(globalThis as any).$app = previousApp+ }+})++test('ingress policies attach to public backends while GCP internal routing preserves the root endpoint', () => {+ const source = (path: string) => readFileSync(new URL(path, import.meta.url), 'utf8')+ const gcp = source('../stack/providers/gcp/api.ts')+ const external = gcp.slice(+ gcp.indexOf("new gcp.compute.BackendService('ApiBackend'"),+ gcp.indexOf("new gcp.compute.URLMap('ApiUrlMap'"),+ )+ assert.match(external, /securityPolicy: internalRoutePolicy.id/)+ const internal = gcp.slice(+ gcp.indexOf("new gcp.compute.RegionBackendService('ApiInternalBackend'"),+ gcp.indexOf("new gcp.compute.RegionUrlMap('ApiInternalUrlMap'"),+ )+ assert.doesNotMatch(internal, /securityPolicy/)+ const expression = gcp.match(/expression: "(request.path.urlDecode\(\).lower\(\)\.matches\('[^']+'\))"/)?.[1]+ assert.ok(expression)+ const argument = expression.match(/\('([^']+)'\)/)![1]+ for (const [path, denied] of [+ ['/internal/v1/credentials/introspect', true],+ ['/api/%69NTERNAL/v1/credentials/introspect', true],+ ['/internal', true],+ ['/api/internal', true],+ ['/api/v1/boxes/internal/start', false],+ ['/api/internal-box', false],+ ] as const) {+ const normalized = decodeURIComponent(path).toLowerCase()+ assert.equal(new RegExp(argument).test(normalized), denied, path)+ }+ assert.match(gcp, /fullPathMatch: '\/internal\/v1\/credentials\/introspect'/)+ assert.match(gcp, /ingress: 'INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER'/)+ assert.match(source('../stack/providers/aws/api.ts'), /denyPublicInternalRoutes\(service.nodes.loadBalancer.arn\)/)+ assert.match(source('../../stack/api.ts'), /denyPublicInternalRoutes\(api.nodes.loadBalancer.arn\)/)+})diff --git a/apps/infra/stack/api.ts b/apps/infra/stack/api.tsindex 10a9e3d89..0324d81aa 100644--- a/apps/infra/stack/api.ts+++ b/apps/infra/stack/api.ts@@ -45,7 +45,8 @@ export interface ApiInputs {clickHouseReadyDependency?: any}-export function buildApi(input: ApiInputs) {+export async function buildApi(input: ApiInputs) {+ const { denyPublicInternalRoutes } = await import('mdeploy/internal-route-policy')const {foundation: { cluster, db, redis, storage },region: REGION,@@ -407,6 +408,8 @@ export function buildApi(input: ApiInputs) {},)+ denyPublicInternalRoutes(api.nodes.loadBalancer.arn)+// Assumed by the Api task role to vend per-org box storage credentials// (see section 3). The permission set mirrors the session policy's action// set in object-storage.service.ts, so the intersection that boxes@@ -436,4 +439,4 @@ export function buildApi(input: ApiInputs) {return { api }}-export type ApiResources = ReturnType<typeof buildApi>+export type ApiResources = Awaited<ReturnType<typeof buildApi>>diff --git a/apps/infra/stack/deploy.ts b/apps/infra/stack/deploy.tsindex e0ca4a7f1..da3d2ca7d 100644--- a/apps/infra/stack/deploy.ts+++ b/apps/infra/stack/deploy.ts@@ -250,7 +250,7 @@ export async function deployStack() {// The stage bootstrap (bootstrap/aws.ts's ensureApiImageRepository) owns the immutable// repository: an image has to be published before a fresh stack can consume one, so the// consumer cannot also be responsible for creating its input.- const { api } = buildApi({+ const { api } = await buildApi({foundation,region: REGION,accountId,diff --git a/apps/infra/stack/registration.test.ts b/apps/infra/stack/registration.test.tsindex 3ddb77d9c..efdf27d16 100644--- a/apps/infra/stack/registration.test.ts+++ b/apps/infra/stack/registration.test.ts@@ -8,14 +8,14 @@ import { all, interpolate, isSecret, output, secret, type Input, type Output } f// Dynamic loading keeps tooling checks independent of SST's generated ambient declarations.const deployModule = new URL('./deploy.ts', import.meta.url).href// Await the Output promise so synthesis errors reject instead of leaving the fixture pending.-const resolved = <T>(value: Input<T>): Promise<T> =>- (output(value) as Output<T> & { promise(): Promise<T> }).promise()+const resolved = <T>(value: Input<T>): Promise<T> => (output(value) as Output<T> & { promise(): Promise<T> }).promise()async function synthesize(environment: Record<string, string | undefined> = {},credential: string | null = 'stored-turnstile-secret',) {const services = new Map<string, Record<string, any>>()+ const resources = new Map<string, Record<string, any>>()const secrets = new Map<string, { value: Output<string>; fallback: string | undefined }>()const pending: Input<unknown>[] = []const globals = globalThis as unknown as Record<string, unknown>@@ -28,6 +28,7 @@ async function synthesize(name: Output<string>arn: Output<string>constructor(name: string, args: Record<string, any> = {}) {+ resources.set(name, args)this.id = output(`${name}-id`)this.name = output<string>(args.name ?? name)this.arn = output(`arn:aws:iam::123456789012:role/${name}`)@@ -37,7 +38,7 @@ async function synthesize(class Secret {value: Output<string>constructor(name: string, fallback?: string) {- const value = name === 'TURNSTILE_SECRET_KEY' ? credential ?? undefined : `stored-${name}`+ const value = name === 'TURNSTILE_SECRET_KEY' ? (credential ?? undefined) : `stored-${name}`const resolvedValue = value ?? fallbackif (resolvedValue === undefined) throw new Error(`Missing SST secret: ${name}`)this.value = secret(resolvedValue)@@ -46,11 +47,14 @@ async function synthesize(}class Service {url: Output<string>- nodes: { taskRole: { arn: Output<string> } }+ nodes: { taskRole: { arn: Output<string> }; loadBalancer: { arn: Output<string> } }constructor(name: string, args: Record<string, any>) {services.set(name, args)this.url = output(`https://${name.toLowerCase()}.example.com/`)- this.nodes = { taskRole: { arn: output(`arn:aws:iam::123456789012:role/${name}`) } }+ this.nodes = {+ taskRole: { arn: output(`arn:aws:iam::123456789012:role/${name}`) },+ loadBalancer: { arn: output(`arn:aws:elasticloadbalancing:region:account:loadbalancer/${name}`) },+ }}}class Vpc extends Resource {@@ -70,9 +74,15 @@ async function synthesize(password = secret('database-password')database = output('boxlite')}- class Redis extends Database { override port = output(6379) }- class RandomPassword { result = secret('generated-password') }- class Router { route() {} }+ class Redis extends Database {+ override port = output(6379)+ }+ class RandomPassword {+ result = secret('generated-password')+ }+ class Router {+ route() {}+ }const replacements = {$app: { name: 'boxlite', stage: 'dev' },$cli: { paths: { root: new URL('..', import.meta.url).pathname } },@@ -83,11 +93,17 @@ async function synthesize(random: { RandomPassword },command: { local: { Command: Resource } },aws: {+ wafv2: { WebAcl: Resource, WebAclAssociation: Resource },getCallerIdentity: async () => ({ accountId: '123456789012' }),getCallerIdentityOutput: () => ({ accountId: output('123456789012') }),getRegionOutput: () => ({ name: output('ap-southeast-1') }),iam: { Role: Resource, RolePolicy: Resource, RolePolicyAttachment: Resource, InstanceProfile: Resource },- ec2: { VpcEndpoint: Resource, SecurityGroup: Resource, Instance: Resource, getAmi: async () => ({ id: 'ami-test' }) },+ ec2: {+ VpcEndpoint: Resource,+ SecurityGroup: Resource,+ Instance: Resource,+ getAmi: async () => ({ id: 'ami-test' }),+ },},sst: {Secret,@@ -116,6 +132,10 @@ async function synthesize(await deployStack()const api = services.get('Api')assert.ok(api, 'deployStack must construct the API service')+ assert.equal(+ await resolved(resources.get('ApiInternalRoutePolicyAssociation')?.resourceArn),+ 'arn:aws:elasticloadbalancing:region:account:loadbalancer/Api',+ )return { environment: api.environment, secrets }} finally {try {diff --git a/apps/libs/ci-listener/README.md b/apps/libs/ci-listener/README.mdindex 21687dbce..b578e219a 100644--- a/apps/libs/ci-listener/README.md+++ b/apps/libs/ci-listener/README.md@@ -1214,6 +1214,11 @@ The runner's GitHub connection is described in GitHub's## Build and test+After a Listener test stops its renewal loop, inspect persisted rows through the+test database snapshot rather than a scheduling lease. That lease can expire+during shutdown. The 64-job accumulation test explicitly expires it before+checking all persisted allocation records; live-operation tests still use fenced reads.+Build and test from the repository root:```shdiff --git a/apps/libs/ci-listener/src/listener.spec.ts b/apps/libs/ci-listener/src/listener.spec.tsindex 8897982d9..db1b170a1 100644--- a/apps/libs/ci-listener/src/listener.spec.ts+++ b/apps/libs/ci-listener/src/listener.spec.ts@@ -6,7 +6,7 @@ import { mkdtempSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { ExecutionJournal } from './execution/journal'-import { ExecutionScope, decodeScope, scopeKey } from './execution/model'+import { ExecutionScope, decodeAllocation, decodeScope, scopeKey } from './execution/model'import { Listener, ListenerBackend, ListenerHost } from './listener'import { JitRegistration } from './runners'import { WorkerPool } from './execution/pool'@@ -508,7 +508,16 @@ describe('CI shared Listener orchestration', () => {}await runUntil(created.promise)expect(create).toHaveBeenCalledTimes(64)- expect((await inspectJournal(state, lease)).allocations.size).toBe(64)+ // The listener has stopped renewing; post-shutdown assertions must tolerate expiry.+ await db.transaction(namespace, async (tx) => {+ const expiry = (await tx.get('@lease', true))!+ await tx.put({ ...expiry, version: randomUUID(), payload: { until: 0 } }, expiry.version)+ })+ const allocations = await db.transaction(namespace, async (tx) =>+ (await tx.page('', 65, 'worker/')).map((row) => decodeAllocation(row.payload)),+ )+ expect(allocations).toHaveLength(64)+ expect(new Set(allocations.map((row) => row.name)).size).toBe(64)})it('reuses each of 64 same-run notice verifications across twelve scheduler pumps', async () => {const pumped = deferred()diff --git a/docs/contributing/architecture/platform/api.md b/docs/contributing/architecture/platform/api.mdindex 5bd721b7e..7d9fa11ab 100644--- a/docs/contributing/architecture/platform/api.md+++ b/docs/contributing/architecture/platform/api.md@@ -581,7 +581,8 @@ There are no automatic transfer retries or redirects. Transfer, authentication,timeout, and invalid-response failures return HTTP 503 with`code: secret_store_unavailable` before any box insertion; plaintext fallback isnever attempted. Logs contain box ID, count, result, and latency, without bodies-or upstream errors. A later insert failure can leave encrypted orphan secrets.+or upstream errors. A later insert failure can leave encrypted orphan secrets;+bounded cleanup requires the separate [lifecycle contract tracked in #2865](https://github.com/boxlite-ai/boxlite/issues/2865).Enable only on staging after the BUI-1385 credential handoff is deployed in anall-v2 environment. Flipping this flag does not migrate existing inline boxes or@@ -591,6 +592,69 @@ of unsupported stored representations and v0 dispatch.Design: [API forwarding](https://github.com/boxlite-ai/boxlite/issues/2736) and[Secret Server write contract](https://github.com/boxlite-ai/boxlite/issues/2626).+### One-time secret credentials (staging)++With `SECRET_SERVER_ENABLED=true`, v2 CREATE_BOX sends a `secretCredential`+containing a `bxsc_` token and `expiresAt`; its `secrets` array contains metadata+without values. The token uses 32 random bytes and expires 15 minutes after issue.+Boxes without secrets receive no credential. START_BOX reuses runtime state.++The `secret_credential` table stores SHA-256 of the complete token, bound to the+runner, Box, organization, and granted secret IDs. The job payload temporarily+stores the bearer token; COMPLETED and FAILED updates remove it in the same+transaction. Run migration `1794873600000` before deploying the API.++`POST /internal/v1/credentials/introspect` accepts `{token, runner_id}`.+One conditional PostgreSQL UPDATE checks the runner, expiry and unused state+while consuming the credential. Success returns `active`, `credential_id`,+`runner_id`, `box_id`, `organization_id`, `grants: [{secret_id}]`, and `expires_at`.+Invalid requests return only `{active:false}`; a wrong runner does not consume+the credential. A second valid request is inactive and logs the credential ID+as a replay warning. Recording logical Box deletion revokes its credentials in+that same transaction, including deletion during checkpoint recovery. Physical+deletion also cascades to credentials. Issuance locks the Box row and checks its+runner, organization and deletion state, so deletion cannot leave a newly issued+credential behind. Credential insertion and CREATE_BOX job insertion share one+transaction; a rejected duplicate job leaves no extra credential. The `box_id`+index bounds revocation and foreign-key cascade lookups to the target Box.++Transactional job creation writes only to PostgreSQL. CREATE_BOX, checkpoint+export/import, and Box migration callers notify the runner after successful+commit, when its job is visible and Box locks are released. Rollback sends no+notification. Redis notification is best effort; failure or a process crash+between commit and notification leaves a durable job for fallback polling.+Nontransactional job creation notifies after its insert commits.++The route has no caller authentication in this MVP and is excluded from OpenAPI.+GCP's external backend denies decoded internal namespace paths using Cloud Armor; only the+private backend passes the exact root route without adding `/api`.+AWS's public ALB denies internal paths with WAF, including dashboard origin traffic.+Both policies match decoded, lowercase `^(?:/api)?/internal(?:/|$)` paths, preserving+public Box routes such as `/api/v1/boxes/internal/start`. Reconcile the AWS bootstrap+deploy policy before rollout so it can manage the stage's credential ingress ACL.+Local deployments must keep the listener on a private or loopback network.+These policies must deploy before enabling Secret Server.++Before merge, verify public rejection on API and dashboard hosts, including `/api`+aliases, mixed case, encoded paths and spoofed Host headers; verify private+redemption of a fresh token. Local tests do not establish deployed isolation.+Observe staging queue delays before rollout: delays beyond 15 minutes fail creation.++The credential expiry limits redemption, not the lifetime of an already fetched+secret. A token that expires before redemption fails creation; there is no reissue+or fetch retry. START_BOX after stop/resume reuses the existing local runtime+configuration; it does not fetch updated secret values or issue another credential.+This requires successful initial fetch and retained runtime state. This API change+alone does not implement Runner-side fetching. Checkpoint creation rejects Boxes+with secrets, so backup/restore through that API is unsupported for them. V2+recoverBox is also unsupported; these paths must not be described as secret refresh.++V0 creation and recovery reject references,+and reject any secrets while the flag is enabled. V2 rejects inline secrets when+enabled and references when disabled; migrate inline Boxes explicitly before rollout.+Never log bearer tokens, hashes or grants. Caller authentication and expiration+cleanup remain outside this MVP; see [design #2735](https://github.com/boxlite-ai/boxlite/issues/2735).+### Hosted routes**Service:** `apps/api` · **Base URL:** `https://api.<domain>/v1` · **Port:** `3000` in