The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(secrets): reuse named organization secrets across Boxes (#3185)
Jiaqiang Wong8a6ef796016c
diff --git a/.github/workflows/README.md b/.github/workflows/README.mdindex f278124d0..e3a78d3a3 100644--- a/.github/workflows/README.md+++ b/.github/workflows/README.md@@ -250,6 +250,12 @@ dashboard-only change reaches Codecov with no report — which the patch statusrejects as a missing report rather than as low coverage. Specs choose their ownenvironment with a `// @vitest-environment jsdom` pragma.+`API Tests` exercises the public organization secret list against the Go Secret+Server and a fresh PostgreSQL database. The job checks Jest's results for both+the five-field metadata test and the 101-record pagination test. To run the same+checks locally, set `SECRET_TEST_DATABASE_URL` to a fresh database and run+`make test:apps:secret-server:secret-list-api`.+`API Tests` also runs the shared CI Listener and standalone host suites, usingthe job's disposable PostgreSQL service through the same `DB_HOST`, `DB_PORT`,`DB_USERNAME`, `DB_PASSWORD` and `DB_DATABASE` settings as other API tests.diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 18fda8c3c..8efaf6eda 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -301,6 +301,7 @@ jobs:- 'make/coverage.mk'- 'make/dev.mk'- 'apps/api/**/!(*.md)'+ - 'apps/secret-server/**/!(*.md|*_test.go)'- 'apps/shared/**/!(*.md)'- 'apps/api/src/cloud-app/agent/**'- 'apps/libs/cloud-app-shared/**'@@ -1244,8 +1245,17 @@ jobs:cache-dependency-path: "apps/yarn.lock"- name: Install app dependenciesrun: "yarn install --immutable"- - name: Install isolated Redis test dependency- run: sudo apt-get -o Acquire::Retries=3 -o APT::Update::Error-Mode=any update && sudo apt-get install -y -o Acquire::Retries=3 redis-server+ - name: Install Redis server and PostgreSQL client for integration tests+ run: sudo apt-get -o Acquire::Retries=3 -o APT::Update::Error-Mode=any update && sudo apt-get install -y -o Acquire::Retries=3 redis-server postgresql-client+ - uses: ./.github/actions/setup-go+ - name: Verify organization secret listing through the public API+ working-directory: .+ env:+ PGPASSWORD: postgres+ SECRET_TEST_DATABASE_URL: postgresql://postgres:[email protected]:5432/secret_list_test+ run: |+ createdb -h 127.0.0.1 -U postgres secret_list_test+ make test:apps:secret-server:secret-list-api- name: Run API unit testsrun: "yarn nx run api:test --coverage --skip-nx-cache"- name: Run shared and standalone CI Listener testsdiff --git a/Cargo.lock b/Cargo.lockindex efcdfc3c8..0361a3f86 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -744,6 +744,7 @@ dependencies = ["napi","napi-build","napi-derive",+ "serde","serde_json","tokio","tracing",diff --git a/apps/api/src/audit/enums/audit-target.enum.ts b/apps/api/src/audit/enums/audit-target.enum.tsindex 9d77fc0f3..991024971 100644--- a/apps/api/src/audit/enums/audit-target.enum.ts+++ b/apps/api/src/audit/enums/audit-target.enum.ts@@ -5,6 +5,7 @@*/export enum AuditTarget {+ SECRET = 'secret',API_KEY = 'api_key',ORGANIZATION = 'organization',ORGANIZATION_INVITATION = 'organization_invitation',diff --git a/apps/api/src/box/box.module.ts b/apps/api/src/box/box.module.tsindex 477c83a24..3429fb00a 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 { BoxSecretCleanupService } from './services/box-secret-cleanup.service'+import { OrgSecretRetirementService } from './services/org-secret-retirement.service'import { SecretCredentialService } from './services/secret-credential.service'import { SecretCredentialController } from './controllers/secret-credential.controller'import { DataSource } from 'typeorm'@@ -125,6 +127,8 @@ import { GcpDiskClient } from './services/gcp-disk-client'FeatureUsageController,],providers: [+ BoxSecretCleanupService,+ OrgSecretRetirementService,SecretCredentialService,SecretServerClient,CheckpointService,@@ -183,6 +187,8 @@ import { GcpDiskClient } from './services/gcp-disk-client'},],exports: [+ OrgSecretRetirementService,+ SecretServerClient,CheckpointService,CheckpointRecoverService,BoxService,diff --git a/apps/api/src/box/dto/create-box.dto.ts b/apps/api/src/box/dto/create-box.dto.tsindex 2afaadf4b..bde389a1d 100644--- a/apps/api/src/box/dto/create-box.dto.ts+++ b/apps/api/src/box/dto/create-box.dto.ts@@ -226,5 +226,5 @@ export class CreateBoxDto {})@IsOptional()@IsArray()- secrets?: BoxSecret[]+ secrets?: (BoxSecret | { secret: string })[]}diff --git a/apps/api/src/box/services/box-secret-cleanup.integration.spec.ts b/apps/api/src/box/services/box-secret-cleanup.integration.spec.tsnew file mode 100644index 000000000..4ee62d5f3--- /dev/null+++ b/apps/api/src/box/services/box-secret-cleanup.integration.spec.ts@@ -0,0 +1,128 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */++import { randomUUID } from 'node:crypto'+import { createServer, Server } from 'node:http'+import { AddressInfo } from 'node:net'+import { CronExpression } from '@nestjs/schedule'+import { SCHEDULE_CRON_OPTIONS } from '@nestjs/schedule/dist/schedule.constants'+import { DataSource } from 'typeorm'+import { BoxSecretCleanup1796083200000 } from '../../migrations/pre-deploy/1796083200000-box-secret-cleanup-migration'+import { SecretServerClient } from './secret-server-client'+import { BoxSecretCleanupService, reserveBoxSecretTransfer } from './box-secret-cleanup.service'++const suite = process.env.DB_HOST ? describe : describe.skip++it('polls for Box secret cleanup every 30 seconds without overlapping callbacks', () => {+ expect(Reflect.getMetadata(SCHEDULE_CRON_OPTIONS, BoxSecretCleanupService.prototype.deliver)).toEqual(+ expect.objectContaining({ cronTime: CronExpression.EVERY_30_SECONDS, waitForCompletion: true }),+ )+})++suite('Box secret cleanup with PostgreSQL and the write HTTP client', () => {+ const org = randomUUID()+ const box = 'Box123456789'+ const schema = 'box_secrets_' + randomUUID().replaceAll('-', '')+ let db: DataSource+ let server: Server+ let worker: BoxSecretCleanupService+ let status: number+ const calls: unknown[] = []+ beforeAll(async () => {+ db = await new DataSource({+ type: 'postgres',+ host: process.env.DB_HOST,+ port: Number(process.env.DB_PORT),+ 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 text PRIMARY KEY, "organizationId" uuid, state text, secrets jsonb)')+ const runner = db.createQueryRunner()+ try {+ await new BoxSecretCleanup1796083200000().up(runner)+ } finally {+ await runner.release()+ }+ server = createServer((req, res) => {+ calls.push([req.method, req.url, req.headers['x-boxlite-organization-id'], req.headers.authorization])+ res.writeHead(status).end()+ })+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ const config = {+ 'secretServer.enabled': true,+ 'secretServer.devToken': 'test-token',+ 'secretServer.url': `http://127.0.0.1:${(server.address() as AddressInfo).port}`,+ }+ worker = new BoxSecretCleanupService(db, new SecretServerClient({ get: (k) => config[k] } as never))+ })+ beforeEach(async () => {+ await db.query('TRUNCATE box, box_secret_cleanup')+ calls.length = 0+ status = 204+ })+ afterAll(async () => {+ server?.closeAllConnections()+ if (server) await new Promise<void>((resolve) => server.close(() => resolve()))+ if (db?.isInitialized) {+ await db.query(`DROP SCHEMA "${schema}" CASCADE`)+ await db.destroy()+ }+ })+ const due = () => db.query('UPDATE box_secret_cleanup SET available_at=now()')+ const tasks = () => db.query('SELECT attempts, creating, available_at > now() AS delayed FROM box_secret_cleanup')+ const insert = (state: string) =>+ db.query('INSERT INTO box VALUES ($1,$2,$3,$4)', [box, org, state, JSON.stringify([{ secretId: randomUUID() }])])++ it('retains across stop and restart, retries a failed delivery after deletion, and acknowledges once', async () => {+ await insert('started')+ for (const state of ['stopped', 'started', 'error']) {+ await db.query('UPDATE box SET state=$1', [state])+ await worker.deliver()+ }+ expect(calls).toEqual([])+ await db.query("UPDATE box SET state='destroyed'")+ status = 503+ await worker.deliver()+ expect(await tasks()).toEqual([{ attempts: 1, creating: false, delayed: true }])+ await db.query('DELETE FROM box')+ await worker.deliver()+ expect(calls).toHaveLength(1)+ await due()+ status = 204+ await worker.deliver()+ await worker.deliver()+ expect(await tasks()).toEqual([])+ const deletion = ['DELETE', '/internal/v1/boxes/' + box + '/secrets', org, 'Bearer test-token']+ expect(calls).toEqual([deletion, deletion])+ })++ it('skips a locked creator, then retires an abandoned transfer and rejects a delayed creator', async () => {+ const claim = await reserveBoxSecretTransfer(db.manager, org, box)+ await due()+ await expect(+ db.transaction(async (manager) => {+ await claim(manager)+ await worker.deliver()+ expect(calls).toHaveLength(0)+ throw new Error('insert failed after transfer')+ }),+ ).rejects.toThrow('insert failed after transfer')+ await worker.deliver()+ expect(calls).toHaveLength(1)+ await expect(db.transaction(claim)).rejects.toThrow('expired')+ })++ it('commits the Box and releases the reservation together when creation wins', async () => {+ const claim = await reserveBoxSecretTransfer(db.manager, org, box)+ await due()+ await db.transaction(async (manager) => {+ await claim(manager)+ await manager.query("INSERT INTO box VALUES ($1,$2,'started','[]')", [box, org])+ })+ await worker.deliver()+ expect(await tasks()).toEqual([])+ expect(calls).toEqual([])+ })+})diff --git a/apps/api/src/box/services/box-secret-cleanup.service.ts b/apps/api/src/box/services/box-secret-cleanup.service.tsnew file mode 100644index 000000000..0401c3bd3--- /dev/null+++ b/apps/api/src/box/services/box-secret-cleanup.service.ts@@ -0,0 +1,67 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */++import { Injectable, Logger, ServiceUnavailableException } from '@nestjs/common'+import { Cron, CronExpression } from '@nestjs/schedule'+import { DataSource, EntityManager } from 'typeorm'+import { SecretServerClient } from './secret-server-client'++// The reservation commits before a remote write. Removing it inside the Box insert+// transaction locks it through publication. A rollback makes it claimable again.+export async function reserveBoxSecretTransfer(manager: EntityManager, org: string, box: string) {+ const owner = [org, box]+ await manager.query(+ `INSERT INTO box_secret_cleanup (organization_id, box_id, creating, available_at)+ VALUES ($1, $2, true, now() + interval '10 minutes')`,+ owner,+ )+ return async (transaction: EntityManager) => {+ const [rows] = await transaction.query(+ 'DELETE FROM box_secret_cleanup WHERE organization_id=$1 AND box_id=$2 AND creating RETURNING box_id',+ owner,+ )+ if (!rows.length) throw new ServiceUnavailableException('Box secret creation attempt has expired')+ }+}++@Injectable()+export class BoxSecretCleanupService {+ private readonly logger = new Logger(BoxSecretCleanupService.name)+ constructor(+ private readonly db: DataSource,+ private readonly store: SecretServerClient,+ ) {}++ @Cron(CronExpression.EVERY_30_SECONDS, { waitForCompletion: true })+ async deliver(): Promise<void> {+ if (!this.store.enabled) return+ await this.db.transaction(async (manager) => {+ const [task] = await manager.query(+ `SELECT organization_id, box_id, creating FROM box_secret_cleanup+ WHERE available_at <= now() ORDER BY available_at LIMIT 1 FOR UPDATE SKIP LOCKED`,+ )+ if (!task) return+ const owner = [task.organization_id, task.box_id]+ // A successful creator removed its reservation atomically with insertion.+ // Expiring this reservation fences any creator resuming after this claim.+ try {+ await this.store.retireBoxSecrets(task.organization_id, task.box_id)+ } catch {+ await manager.query(+ `UPDATE box_secret_cleanup SET creating=false, attempts=attempts+1,+ available_at=now() + make_interval(secs => LEAST(3600, 5 * (1 << LEAST(attempts,10))))+ WHERE organization_id=$1 AND box_id=$2`,+ owner,+ )+ this.logger.warn(`Secret cleanup pending retry for Box ${task.box_id}`)+ return+ }+ if (!task.creating) {+ await manager.query(+ `UPDATE box SET secrets='[]' WHERE "organizationId"=$1 AND id=$2 AND state='destroyed'`,+ owner,+ )+ }+ await manager.query('DELETE FROM box_secret_cleanup WHERE organization_id=$1 AND box_id=$2', owner)+ })+ }+}diff --git a/apps/api/src/box/services/box.service.spec.ts b/apps/api/src/box/services/box.service.spec.tsindex d461ffbd4..cb4b61b9d 100644--- a/apps/api/src/box/services/box.service.spec.ts+++ b/apps/api/src/box/services/box.service.spec.ts@@ -483,7 +483,7 @@ describe('BoxService inbound defaults', () => {transfer = {boxId: request.url.split('/')[4],payload: JSON.parse(Buffer.concat(chunks).toString()),- insertCalls: boxRepository.insert.mock.calls.length,+ insertCalls: persist.mock.calls.length,}if (status === -1) {response.writeHead(201)@@ -506,12 +506,22 @@ describe('BoxService inbound defaults', () => {const { service, boxRepository, warmPoolService } = makeCreateService({secretServerClient: new SecretServerClient({ get: (key: string) => values[key] } as any),})+ const persist = jest.fn(async (box) => box)+ const manager = { query: jest.fn(async () => [[{ box_id: 'claimed' }], 1]) }+ Object.assign(boxRepository, { manager })+ boxRepository.insert.mockImplementation(async (box, _limit, callback, initialize) => {+ await initialize?.(manager)+ await persist(box)+ await callback?.(manager, box)+ return box+ })const events = (service as any).eventEmitterreturn {service,boxRepository,warmPoolService,events,+ persist,transfer: () => transfer,close: async () => {server.closeAllConnections()@@ -524,9 +534,8 @@ describe('BoxService inbound defaults', () => {const f = await fixture()const onPersist = jest.fn()const snapshots: unknown[] = []- f.boxRepository.insert.mockImplementation(async (box, _limit, callback) => {+ f.persist.mockImplementation(async (box) => {snapshots.push(structuredClone(box.secrets))- await callback({}, box)return box})try {@@ -567,7 +576,7 @@ describe('BoxService inbound defaults', () => {await expect(f.service.create({ name: 'refused', secrets }, activeOrg, Context.user(), { createdBy: 'user' }),).rejects.toMatchObject({ status: 503, response: { code: 'secret_store_unavailable' } })- expect(f.boxRepository.insert).not.toHaveBeenCalled()+ expect(f.persist).not.toHaveBeenCalled()expect(f.events.emitAsync).not.toHaveBeenCalled()} finally {await f.close()@@ -632,7 +641,7 @@ describe('BoxService inbound defaults', () => {it('keeps plaintext out of failed inserts and emits no creation event', async () => {const f = await fixture()- f.boxRepository.insert.mockRejectedValue(new Error('insert failed'))+ f.persist.mockRejectedValue(new Error('insert failed'))try {await expect(f.service.create({ name: 'failed-insert', secrets }, activeOrg, Context.user(), { createdBy: 'user' }),diff --git a/apps/api/src/box/services/box.service.ts b/apps/api/src/box/services/box.service.tsindex 47cf31425..b93da1ede 100644--- a/apps/api/src/box/services/box.service.ts+++ b/apps/api/src/box/services/box.service.ts@@ -111,6 +111,7 @@ import { BoxActivityService } from './box-activity.service'import { assertWithinPerBoxLimits } from './per-box-limits'import { OrganizationBoxLimitsService } from '../../organization/services/organization-box-limits.service'import { requiresFreshBox } from '../utils/warm-pool-eligibility.util'+import { reserveBoxSecretTransfer } from './box-secret-cleanup.service'import { SecretServerClient } from './secret-server-client'import { OutboundPolicy, setRunnerOutbound } from '../runner-adapter/network-policy'import { isCuratedSelector, withoutRegistryProxy } from '../../image/utils/image-ref.util'@@ -148,7 +149,7 @@ export type BoxCreationOptions = {export type ProxyAdmission = (box: Box, boxId: string) => void-function validateSecrets(secrets: BoxSecret[] | undefined): void {+export function validateSecrets(secrets: BoxSecret[] | undefined): void {const forbidden = new Set(['host','connection',@@ -178,7 +179,7 @@ function validateSecrets(secrets: BoxSecret[] | undefined): void {if (!headers || typeof headers !== 'object' || Array.isArray(headers) || Object.keys(headers).length === 0) {throw new BadRequestError(`secret ${JSON.stringify(secret.name)} has no headers; recreate the box with headers`)}- if (typeof secret.value !== 'string' || controls.test(secret.value)) {+ if (!secret.secretId && (typeof secret.value !== 'string' || controls.test(secret.value))) {throw new BadRequestError(`Secret ${secret.name} has an invalid header value`)}const ownHeaders = new Set<string>()@@ -333,7 +334,6 @@ export class BoxService {organization = Object.assign(Object.create(Object.getPrototypeOf(organization)) as Organization, organization, {nestedVirtualizationEnabled,})- validateSecrets(createBoxDto.secrets)const outboundEnabled = createBoxDto.outboundEnabled ?? !organization.boxLimitedNetworkEgressif (hasDisabledOutboundRules(outboundEnabled ? 'enabled' : 'disabled', createBoxDto.outboundAllowNet)) {throw new BadRequestError(DISABLED_OUTBOUND_RULES_ERROR)@@ -354,6 +354,10 @@ export class BoxService {assertWithinPerBoxLimits(cpu, mem, disk, limits)this.organizationService.assertOrganizationIsNotSuspended(organization)+ const entries = createBoxDto.secrets ?? []+ const secrets = entries.length ? await this.secretServerClient.resolveForBox(organization.id, entries) : []+ validateSecrets(secrets)+// Admission decides whether this organization may boot from this image at// all; it is the gate that replaced "curated images only". It runs after// the suspension check, and before the resolver, so a refused image never@@ -500,12 +504,26 @@ export class BoxService {// Complete local validation before transferring values. Only references// may reach insertion, transactional callbacks, or creation events.- box.secrets = await this.secretServerClient.storeBoxSecrets(- box.id,- organization.id,- options.createdBy,- createBoxDto.secrets || [],- )+ const inline = secrets.filter((secret) => !secret.secretId)+ if (this.secretServerClient.enabled) this.secretServerClient.validateInline(inline)+ const claim =+ inline.length && this.secretServerClient.enabled+ ? await reserveBoxSecretTransfer(this.boxRepository.manager, organization.id, box.id)+ : undefined+ const initialize = claim+ ? async (manager: EntityManager) => {+ await claim(manager)+ const stored = await this.secretServerClient.storeBoxSecrets(+ box.id,+ organization.id,+ options.createdBy,+ inline,+ )+ let inlineIndex = 0+ box.secrets = secrets.map((secret) => (secret.secretId ? secret : stored[inlineIndex++]))+ }+ : undefined+ box.secrets = claim ? [] : secrets// No caller-provided name -> assign a fun default (e.g. "cozy-otter"),// falling back to "cozy-otter-{boxId}" if it collides with the per-org@@ -525,9 +543,11 @@ export class BoxService {const insertedBox = await this.persistOnAvailableRunner(box, { regions: [region.id], boxClass }, async () => {coldPullTicket = await this.imageAdmissionService.spendColdPullBudget(organization, resolvedImage)const insert = () =>- options.onPersist- ? this.boxRepository.insert(box, options.maxCreatedBoxes, options.onPersist)- : this.boxRepository.insert(box, options.maxCreatedBoxes)+ initialize+ ? this.boxRepository.insert(box, options.maxCreatedBoxes, options.onPersist, initialize)+ : options.onPersist+ ? this.boxRepository.insert(box, options.maxCreatedBoxes, options.onPersist)+ : this.boxRepository.insert(box, options.maxCreatedBoxes)return createBoxDto.name? insert(): persistWithGeneratedBoxName(box.id, (name) => {@@ -550,6 +570,7 @@ export class BoxService {if (insertedBox.state === BoxState.STARTED) options.onStarted?.()return this.toBoxDto(insertedBox)} catch (error) {+ if (error.code === 'BS001') throw new ConflictException('Referenced secret is being deleted or has been deleted')if (error.code === '23505') {throw new ConflictException(createBoxDto.namediff --git a/apps/api/src/box/services/checkpoint.integration.spec.ts b/apps/api/src/box/services/checkpoint.integration.spec.tsindex 164dbad00..f744d7ba1 100644--- a/apps/api/src/box/services/checkpoint.integration.spec.ts+++ b/apps/api/src/box/services/checkpoint.integration.spec.ts@@ -1,3 +1,4 @@+import { BoxSecretCleanup1796083200000 } from '../../migrations/pre-deploy/1796083200000-box-secret-cleanup-migration'import { SecretCredentialService } from './secret-credential.service'import { AddSecretCredential1794873600000 } from '../../migrations/pre-deploy/1794873600000-add-secret-credential-migration'// Copyright 2026 BoxLite AI@@ -107,6 +108,7 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>const migrationRunner = dataSource.createQueryRunner()try {await new AddSecretCredential1794873600000().up(migrationRunner)+ await new BoxSecretCleanup1796083200000().up(migrationRunner)} finally {await migrationRunner.release()}@@ -1078,11 +1080,25 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>expect(archiveStore.remove).not.toHaveBeenCalled()const ordinary = await source('ordinary-error')const old = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000)- await boxes.update(target.id, { updatedAt: old })- await boxes.update(ordinary.id, { state: BoxState.ERROR, desiredState: BoxDesiredState.DESTROYED, updatedAt: old })+ const refs = [+ { name: 'key', hosts: ['example.org'], secretId: randomUUID(), headers: { Authorization: '{value}' } },+ ]+ await boxes.update(target.id, { secrets: refs, updatedAt: old })+ await boxes.update(ordinary.id, {+ secrets: refs,+ state: BoxState.ERROR,+ desiredState: BoxDesiredState.DESTROYED,+ updatedAt: old,+ })await lifecycleService().cleanupStaleErrorBoxes()expect(await boxes.findOneBy({ id: target.id })).not.toBeNull()expect(await boxes.findOneBy({ id: ordinary.id })).toBeNull()+ expect(+ await dataSource.query('SELECT organization_id, box_id FROM box_secret_cleanup WHERE box_id IN ($1, $2)', [+ ordinary.id,+ target.id,+ ]),+ ).toEqual([{ organization_id: organizationId, box_id: ordinary.id }])})it('protects the selected registry login through a checkpoint without blocking a shadowed prefix', async () => {diff --git a/apps/api/src/box/services/org-secret-retirement.integration.spec.ts b/apps/api/src/box/services/org-secret-retirement.integration.spec.tsnew file mode 100644index 000000000..e5657d971--- /dev/null+++ b/apps/api/src/box/services/org-secret-retirement.integration.spec.ts@@ -0,0 +1,245 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */++import { randomUUID } from 'node:crypto'+import { NotFoundException, ServiceUnavailableException } from '@nestjs/common'+import { DataSource, EntityManager } from 'typeorm'+import { OrgSecretRetirement1796169600000 } from '../../migrations/pre-deploy/1796169600000-org-secret-retirement-migration'+import { OrgSecretRetirementService } from './org-secret-retirement.service'+import { SecretServerClient } from './secret-server-client'++const suite = process.env.DB_HOST ? describe : describe.skip++suite.each(['read committed', 'repeatable read'])(+ 'organization secret retirement with PostgreSQL (%s)',+ (isolation) => {+ const org = randomUUID()+ const foreign = randomUUID()+ const id = randomUUID()+ const schema = 'org_secret_' + randomUUID().replaceAll('-', '')+ let db: DataSource+ let service: OrgSecretRetirementService+ const store = { enabled: true, checkOrganizationSecret: jest.fn(), deleteOrganizationSecret: jest.fn() }+ const bind = (manager: EntityManager, state = 'started', secret: string = id) =>+ manager.query('INSERT INTO box VALUES ($1,$2,$3,$4) RETURNING id', [+ randomUUID(),+ org,+ state,+ JSON.stringify([{ secretId: secret }]),+ ])++ beforeAll(async () => {+ db = await new DataSource({+ type: 'postgres',+ host: process.env.DB_HOST,+ port: Number(process.env.DB_PORT),+ username: process.env.DB_USERNAME,+ password: process.env.DB_PASSWORD,+ database: process.env.DB_DATABASE,+ extra: {+ options: `-c search_path=${schema} -c default_transaction_isolation=${isolation.replace(' ', '\\ ')}`,+ },+ }).initialize()+ await db.query(`CREATE SCHEMA "${schema}"`)+ await db.query('CREATE TABLE box(id text PRIMARY KEY, "organizationId" uuid, state text, secrets jsonb)')+ const migration = db.createQueryRunner()+ try {+ await new OrgSecretRetirement1796169600000().up(migration)+ } finally {+ await migration.release()+ }+ service = new OrgSecretRetirementService(db, store as unknown as SecretServerClient)+ })+ beforeEach(async () => {+ await db.query('TRUNCATE box, org_secret_retirement')+ store.checkOrganizationSecret.mockReset().mockResolvedValue(undefined)+ store.deleteOrganizationSecret.mockReset().mockResolvedValue(undefined)+ })+ afterAll(async () => {+ if (db?.isInitialized) {+ await db.query(`DROP SCHEMA "${schema}" CASCADE`)+ await db.destroy()+ }+ })++ const live = process.env.SECRET_SERVER_URL && process.env.SECRET_SERVER_DEV_TOKEN ? it : it.skip+ live('manages a shared secret through the real write service with two Box records', async () => {+ const config = {+ 'secretServer.enabled': true,+ 'secretServer.url': process.env.SECRET_SERVER_URL,+ 'secretServer.devToken': process.env.SECRET_SERVER_DEV_TOKEN,+ }+ const client = new SecretServerClient({ get: (key) => config[key] } as never)+ const removal = new OrgSecretRetirementService(db, client)+ const policy = {+ hosts: ['service.example'],+ headers: { 'X-Key': '{value}' },+ placeholder: 'shared-marker',+ }+ const secret = { name: 'shared', value: 'integration-value', ...policy }+ const shared = await client.createOrganizationSecret(org, 'test', secret)+ const listed = { ...shared, ...policy }+ expect(await client.listOrganizationSecrets(org, undefined, 2)).toEqual([listed])+ expect(await client.listOrganizationSecrets(foreign, undefined, 2)).toEqual([])+ await expect(removal.remove(foreign, shared.id)).rejects.toMatchObject({ status: 404 })+ const boxID = 'A' + randomUUID().replaceAll('-', '').slice(0, 11)+ const [privateRef] = await client.storeBoxSecrets(boxID, org, 'test', [{ ...secret, name: 'private' }])+ const resolve = () => client.resolveForBox(org, [{ secret: 'shared' }])+ const sharedRef = await resolve()+ const insert = (box: string, refs: unknown[]) =>+ db.query("INSERT INTO box VALUES ($1,$2,'started',$3)", [box, org, JSON.stringify(refs)])+ await insert(boxID, [privateRef, ...sharedRef])+ await insert('B', await resolve())+ await expect(removal.remove(org, privateRef.secretId)).rejects.toMatchObject({ status: 404 })+ expect(await client.listOrganizationSecrets(org, undefined, 10)).toEqual([listed])+ await db.query("UPDATE box SET state='stopped' WHERE id=$1", [boxID])+ await expect(removal.remove(org, shared.id)).rejects.toMatchObject({ status: 409 })+ await db.query("UPDATE box SET state='destroyed' WHERE id=$1", [boxID])+ await client.retireBoxSecrets(org, boxID)+ await expect(removal.remove(org, shared.id)).rejects.toMatchObject({ status: 409 })+ expect(await resolve()).toEqual(sharedRef)+ await db.query("DELETE FROM box WHERE id='B'")+ await removal.remove(org, shared.id)+ await expect(resolve()).rejects.toMatchObject({ status: 404 })+ expect(await client.listOrganizationSecrets(org, undefined, 2)).toEqual([])+ const replacement = await client.createOrganizationSecret(org, 'test', secret)+ expect(replacement.id).not.toBe(shared.id)+ await removal.remove(org, shared.id)+ expect(await client.listOrganizationSecrets(org, undefined, 2)).toEqual([{ ...replacement, ...policy }])+ await removal.remove(org, replacement.id)+ })++ it('protects every Box until its actual destruction and keeps repeat deletion scoped to its owner', async () => {+ const [first] = await bind(db.manager, 'started', id.toUpperCase())+ await bind(db.manager, 'stopped')+ for (const state of ['started', 'stopped', 'destroying', 'error']) {+ await db.query('UPDATE box SET state=$1 WHERE id=$2', [state, first.id])+ await expect(service.remove(org, id)).rejects.toMatchObject({ status: 409 })+ }+ // A disappeared, B is still stopped and retains the ID for restart.+ await db.query('DELETE FROM box WHERE id=$1', [first.id])+ await expect(service.remove(org, id)).rejects.toMatchObject({ status: 409 })+ expect(store.deleteOrganizationSecret).not.toHaveBeenCalled()+ await db.query("UPDATE box SET state='destroyed'")+ await service.remove(org, id)+ await service.remove(org, id)+ expect(store.deleteOrganizationSecret.mock.calls).toEqual([[org, id]])+ store.checkOrganizationSecret.mockRejectedValueOnce(new NotFoundException('Secret not found'))+ await expect(service.remove(foreign, id)).rejects.toMatchObject({ status: 404 })+ expect(store.checkOrganizationSecret).toHaveBeenLastCalledWith(foreign, id)+ })++ it('checks ownership before considering any reference to a private or unknown ID', async () => {+ await bind(db.manager)+ store.checkOrganizationSecret.mockRejectedValue(new NotFoundException('Secret not found'))+ await expect(service.remove(org, id)).rejects.toMatchObject({ status: 404 })+ expect(await db.query('SELECT * FROM org_secret_retirement')).toHaveLength(0)+ expect(store.deleteOrganizationSecret).not.toHaveBeenCalled()+ })++ it('waits for a Box publication that already holds the binding lock', async () => {+ const tx = db.createQueryRunner()+ await tx.startTransaction()+ let deletion: Promise<void>+ try {+ await bind(tx.manager)+ deletion = service.remove(org, id)+ const [lock] = await tx.query(+ "SELECT classid, objid FROM pg_locks WHERE pid=pg_backend_pid() AND locktype='advisory'",+ )+ // Observe the real DELETE transaction waiting before making the Box visible.+ const deadline = Date.now() + 4000+ for (;;) {+ const [row] = await db.query(+ "SELECT EXISTS (SELECT FROM pg_locks WHERE locktype='advisory' AND classid=$1 AND objid=$2 AND NOT granted) AS waiting",+ [lock.classid, lock.objid],+ )+ if (row.waiting) break+ if (Date.now() >= deadline) throw new Error('delete did not wait for the pending Box')+ await new Promise((resolve) => setTimeout(resolve, 10))+ }+ await tx.commitTransaction()+ await expect(deletion).rejects.toMatchObject({ status: 409 })+ } finally {+ if (tx.isTransactionActive) await tx.rollbackTransaction()+ await tx.release()+ }+ expect(store.deleteOrganizationSecret).not.toHaveBeenCalled()+ })++ it('rejects a Box writer whose transaction snapshot predates the committed deletion', async () => {+ await db.transaction(async (manager) => {+ const [snapshot] = await manager.query(`SELECT current_setting('transaction_isolation') AS isolation,+ count(*)::int AS markers FROM org_secret_retirement`)+ expect(snapshot).toEqual({ isolation, markers: 0 })+ await service.remove(org, id)+ await expect(bind(manager)).rejects.toMatchObject({ code: 'BS001' })+ })+ expect(await db.query('SELECT id FROM box')).toEqual([])+ })++ it('allows concurrent Boxes to publish the same two IDs in opposite orders', async () => {+ const other = randomUUID()+ const insert = (ids: string[]) =>+ db.query('INSERT INTO box VALUES ($1,$2,$3,$4)', [+ randomUUID(),+ org,+ 'started',+ JSON.stringify(ids.map((secretId) => ({ secretId }))),+ ])+ await Promise.all([insert([id, other]), insert([other, id])])+ expect(await db.query('SELECT id FROM box')).toHaveLength(2)+ expect(await db.query('SELECT secret_id FROM org_secret_retirement')).toHaveLength(0)+ await expect(service.remove(org, id)).rejects.toMatchObject({ status: 409 })+ await expect(service.remove(org, other)).rejects.toMatchObject({ status: 409 })+ })++ it('blocks a stale binding before and after deletion, and accepts a replacement ID', async () => {+ let entered: () => void+ let release: () => void+ const checked = new Promise<void>((resolve) => {+ entered = resolve+ })+ const resume = new Promise<void>((resolve) => {+ release = resolve+ })+ store.checkOrganizationSecret.mockImplementationOnce(async () => {+ entered()+ await resume+ })+ const deletion = service.remove(org, id)+ try {+ await checked+ await expect(bind(db.manager)).rejects.toMatchObject({ code: 'BS001' })+ } finally {+ release()+ await deletion+ }+ await expect(bind(db.manager)).rejects.toMatchObject({ code: 'BS001' })+ await bind(db.manager, 'started', randomUUID())+ expect(await db.query('SELECT id FROM box')).toHaveLength(1)+ })++ it('recovers after a lost deletion response and confirms a client retry without deleting twice more', async () => {+ store.deleteOrganizationSecret+ .mockRejectedValueOnce(new ServiceUnavailableException())+ .mockRejectedValueOnce(new ServiceUnavailableException())+ await expect(service.remove(org, id)).rejects.toMatchObject({ status: 503 })+ await expect(bind(db.manager)).rejects.toMatchObject({ code: 'BS001' })+ await service.retry()+ expect(await db.query('SELECT retry_at > now() AS delayed FROM org_secret_retirement')).toEqual([+ { delayed: true },+ ])+ await service.retry()+ expect(store.deleteOrganizationSecret).toHaveBeenCalledTimes(2)+ await db.query('UPDATE org_secret_retirement SET retry_at=now()')+ await service.retry()+ await service.remove(org, id)+ expect(store.deleteOrganizationSecret.mock.calls).toEqual([+ [org, id],+ [org, id],+ [org, id],+ ])+ expect(store.checkOrganizationSecret).toHaveBeenCalledTimes(1)+ })+ },+)diff --git a/apps/api/src/box/services/org-secret-retirement.service.ts b/apps/api/src/box/services/org-secret-retirement.service.tsnew file mode 100644index 000000000..b9742e54d--- /dev/null+++ b/apps/api/src/box/services/org-secret-retirement.service.ts@@ -0,0 +1,67 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */++import { ConflictException, Injectable, Logger } from '@nestjs/common'+import { Cron, CronExpression } from '@nestjs/schedule'+import { DataSource, EntityManager } from 'typeorm'+import { SecretServerClient } from './secret-server-client'++@Injectable()+export class OrgSecretRetirementService {+ private readonly logger = new Logger(OrgSecretRetirementService.name)+ constructor(+ private readonly db: DataSource,+ private readonly store: SecretServerClient,+ ) {}++ async remove(org: string, id: string): Promise<void> {+ // The usage query must see a Box that committed while the deletion waited for its lock.+ const completed = await this.db.transaction('READ COMMITTED', async (manager) => {+ // Matches the shared lock held through publication of each Box binding.+ await manager.query('SELECT pg_advisory_xact_lock(hashtext($1::uuid::text), hashtext($2::uuid::text))', [org, id])+ const [prior] = await manager.query(+ 'SELECT retry_at IS NULL AS completed FROM org_secret_retirement WHERE organization_id=$1 AND secret_id=$2',+ [org, id],+ )+ if (prior) return prior.completed+ await this.store.checkOrganizationSecret(org, id)+ const [usage] = await manager.query(+ `SELECT EXISTS(SELECT FROM box WHERE "organizationId"=$1 AND state <> 'destroyed'+ AND EXISTS (SELECT FROM jsonb_array_elements(secrets) binding WHERE lower(binding->>'secretId')=$2::uuid::text)) AS in_use`,+ [org, id],+ )+ if (usage.in_use) throw new ConflictException('Secret is in use by a Box')+ await manager.query('INSERT INTO org_secret_retirement (organization_id, secret_id) VALUES ($1,$2)', [org, id])+ return false+ })+ if (!completed) await this.deliver(this.db.manager, org, id)+ }++ private async deliver(manager: EntityManager, org: string, id: string): Promise<void> {+ await this.store.deleteOrganizationSecret(org, id)+ // Keep the ID even when delivery succeeds. A delayed creator may already have resolved it.+ await manager.query('UPDATE org_secret_retirement SET retry_at=NULL WHERE organization_id=$1 AND secret_id=$2', [+ org,+ id,+ ])+ }++ @Cron(CronExpression.EVERY_30_SECONDS, { waitForCompletion: true })+ async retry(): Promise<void> {+ if (!this.store.enabled) return+ await this.db.transaction(async (manager) => {+ const [task] = await manager.query(`SELECT organization_id, secret_id FROM org_secret_retirement+ WHERE retry_at <= now() ORDER BY retry_at LIMIT 1 FOR UPDATE SKIP LOCKED`)+ if (!task) return+ try {+ await this.deliver(manager, task.organization_id, task.secret_id)+ } catch {+ await manager.query(+ `UPDATE org_secret_retirement SET retry_at=now()+interval '30 seconds'+ WHERE organization_id=$1 AND secret_id=$2`,+ [task.organization_id, task.secret_id],+ )+ this.logger.warn('Organization secret removal pending retry')+ }+ })+ }+}diff --git a/apps/api/src/box/services/secret-server-client.spec.ts b/apps/api/src/box/services/secret-server-client.spec.tsindex 0ebb7c1f5..16544af76 100644--- a/apps/api/src/box/services/secret-server-client.spec.ts+++ b/apps/api/src/box/services/secret-server-client.spec.ts@@ -41,7 +41,7 @@ describe('SecretServerClient HTTP boundary', () => {server = createServer(async (request, response) => {const chunks: Buffer[] = []for await (const chunk of request) chunks.push(chunk)- const body = JSON.parse(Buffer.concat(chunks).toString())+ const body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString()) : undefinedrequests.push({ path: request.url, authorization: request.headers.authorization, body })respond(response, body)})@@ -71,6 +71,153 @@ describe('SecretServerClient HTTP boundary', () => {await new Promise<void>((resolve) => server.close(() => resolve()))})+ it('creates an organization secret and returns its identity', async () => {+ respond = (response) => {+ response.writeHead(201)+ response.end(JSON.stringify({ id: ids[0], name: secrets[0].name }))+ }+ await expect(client(url).createOrganizationSecret('org-a', 'creator', secrets[0])).resolves.toEqual({+ id: ids[0],+ name: secrets[0].name,+ })+ expect(requests).toEqual([+ {+ path: '/internal/v1/organizations/org-a/secrets',+ authorization: 'Bearer dev-token',+ body: { created_by: 'creator', secret: { ...secrets[0], placeholder: '<BOXLITE_SECRET:first>' } },+ },+ ])+ })++ const listItem = {+ id: ids[1],+ name: 'second',+ hosts: ['api.example'],+ headers: { Authorization: 'Bearer {value}' },+ placeholder: 'custom-marker',+ }+ it('returns only the stored identity, hosts, header templates and placeholder', async () => {+ respond = (res) => res.end(JSON.stringify({ secrets: [{ ...listItem, value: 'extra' }] }))+ const store = client(url)+ await expect(store.listOrganizationSecrets('org-a', ids[0], 2)).resolves.toEqual([listItem])+ expect(requests[0]).toEqual({+ path: '/internal/v1/organizations/org-a/secrets?limit=2&after=' + ids[0],+ authorization: 'Bearer dev-token',+ body: undefined,+ })+ })++ it.each([+ { id: 'invalid' },+ { name: '' },+ { hosts: undefined },+ { hosts: [1] },+ { headers: null },+ { headers: [] },+ { headers: { Authorization: 1 } },+ { placeholder: undefined },+ ])('rejects malformed list metadata (%j)', async (invalid) => {+ respond = (res) => res.end(JSON.stringify({ secrets: [{ ...listItem, ...invalid }] }))+ await expect(client(url).listOrganizationSecrets('org-a', undefined, 2)).rejects.toThrow(+ 'Invalid secret store response',+ )+ })++ it.each([+ [409, 409, 'Secret name is already in use'],+ [422, 400, 'Invalid organization secret'],+ [500, 503, 'Secret store unavailable'],+ ] as const)('maps organization creation failure %i to HTTP %i', async (upstream, status, message) => {+ respond = (res) => res.writeHead(upstream).end('upstream details')+ await expect(client(url).createOrganizationSecret('org-a', 'creator', secrets[0])).rejects.toMatchObject({+ status,+ message,+ })+ })++ it.each([+ { id: 'not-a-uuid', name: 'first' },+ { id: ids[0], name: 'different' },+ ])('rejects mismatched identities in a successful create response (%j)', async (identity) => {+ respond = (res) => res.writeHead(201).end(JSON.stringify(identity))+ await expect(client(url).createOrganizationSecret('org-a', 'creator', secrets[0])).rejects.toMatchObject({+ status: 503,+ message: 'Invalid secret store response',+ })+ })++ it('rejects a list response that exceeds the requested limit', async () => {+ const items = ids.map((id, i) => ({ ...listItem, id, name: secrets[i].name }))+ respond = (res) => res.end(JSON.stringify({ secrets: items }))+ await expect(client(url).listOrganizationSecrets('org-a', undefined, 1)).rejects.toMatchObject({+ status: 503,+ message: 'Invalid secret store response',+ })+ })++ it('resolves only names and preserves mixed input order and saved policy', async () => {+ const ref = {+ id: ids[0],+ name: 'Service-Key',+ hosts: ['auth.example'],+ headers: { 'X-Key': '{value}' },+ placeholder: 'shared-marker',+ }+ respond = (response) => response.end(JSON.stringify({ secrets: [ref] }))+ const values = await client(url).resolveForBox('org-a', [secrets[0], { secret: 'service_key' }, secrets[1]])+ expect(requests[0]).toEqual({+ path: '/internal/v1/organizations/org-a/secrets/resolve',+ authorization: 'Bearer dev-token',+ body: { names: ['service_key'] },+ })+ const { id, ...policy } = ref+ expect(values).toEqual([secrets[0], { ...policy, secretId: id }, secrets[1]])+ })++ it('rejects unavailable names, colliding mixed names and caller-supplied IDs', async () => {+ respond = (response) => {+ response.writeHead(404)+ response.end()+ }+ await expect(client(url).resolveForBox('org-b', [{ secret: 'absent' }])).rejects.toThrow('Secret not found')+ await expect(client(url).resolveForBox('org-a', [secrets[0], { secret: 'FIRST' }])).rejects.toThrow('duplicate')+ await expect(client(url).resolveForBox('org-a', [{ ...secrets[0], secretId: ids[0] }])).rejects.toThrow(+ 'server-assigned',+ )+ expect(requests).toHaveLength(1)+ })++ it('rejects extra fields and oversized mixed batches before requesting secret IDs', async () => {+ const store = client(url)+ const override = { secret: 'shared', value: 'override' }+ await expect(store.resolveForBox('org-a', [override])).rejects.toThrow('accepts only a name')+ const names = Array.from({ length: 64 }, (_, i) => ({ secret: 'shared_' + i }))+ await expect(store.resolveForBox('org-a', [secrets[0], ...names])).rejects.toThrow('at most 64')+ expect(requests).toHaveLength(0)+ })++ describe('organization secret resolution responses', () => {+ const policy = { hosts: ['api.example'], headers: { 'X-Key': '{value}' }, placeholder: 'dummy' }+ const first = { ...policy, id: ids[0], name: 'first' }+ const second = { ...policy, id: ids[1], name: 'second' }+ it.each([+ ['missing result', [first]],+ ['different order', [second, first]],+ ['repeated ID', [first, { ...second, id: first.id }]],+ ['empty host', [first, { ...second, hosts: [''] }]],+ ['missing placeholder', [first, { ...second, placeholder: '' }]],+ ['missing headers', [first, { ...second, headers: null }]],+ ])('rejects a %s instead of returning a partial binding', async (_, entries) => {+ respond = (res) => res.end(JSON.stringify({ secrets: entries }))+ await expect(+ client(url).resolveForBox('org-a', [{ secret: 'first' }, { secret: 'second' }]),+ ).rejects.toMatchObject({+ status: 503,+ message: 'Invalid secret store response',+ })+ })+ })+it.each([200, 201])('matches a reordered %s response without copying values', async (status) => {successStatus = statusconst result = await client(url).storeBoxSecrets('Ab12Cd34Ef56', 'org-id', 'user-id', secrets)diff --git a/apps/api/src/box/services/secret-server-client.ts b/apps/api/src/box/services/secret-server-client.tsindex 68f2e5ffd..8aa69e3c8 100644--- a/apps/api/src/box/services/secret-server-client.ts+++ b/apps/api/src/box/services/secret-server-client.ts@@ -1,6 +1,13 @@/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */-import { Injectable, Logger, ServiceUnavailableException } from '@nestjs/common'+import {+ BadRequestException,+ ConflictException,+ Injectable,+ Logger,+ NotFoundException,+ ServiceUnavailableException,+} from '@nestjs/common'import { GoogleAuth } from 'google-auth-library'import { TypedConfigService } from '../../config/typed-config.service'import { BoxSecret } from '../dto/box.dto'@@ -9,6 +16,24 @@ import { BadRequestError } from '../../exceptions/bad-request.exception'const TRANSFER_TIMEOUT_MS = 6000const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i+export type NamedSecret = { secret: string }+export type OrganizationSecretIdentity = { id: string; name: string }+type OrganizationSecretListItem = OrganizationSecretIdentity & {+ hosts: string[]+ headers: Record<string, string>+ placeholder: string+}++function normalizedName(name: string): string {+ return name.replace(/[a-z]/g, (letter) => letter.toUpperCase()).replace(/[^A-Z0-9_]/gu, '_')+}++class SecretResponseError extends Error {+ constructor(readonly status: number) {+ super()+ }+}+@Injectable()export class SecretServerClient {private readonly logger = new Logger(SecretServerClient.name)@@ -16,19 +41,25 @@ export class SecretServerClient {constructor(private readonly config: TypedConfigService) {}- async storeBoxSecrets(- boxId: string,- orgId: string,- createdBy: string | undefined,- secrets: BoxSecret[],- ): Promise<BoxSecret[]> {- if (!this.config.get('secretServer.enabled') || secrets.length === 0) return secrets+ get enabled(): boolean {+ return this.config.get('secretServer.enabled')+ }++ async retireBoxSecrets(orgId: string, boxId: string): Promise<void> {+ await this.withDeadline(async (signal) => {+ const path = `/internal/v1/boxes/${encodeURIComponent(boxId)}/secrets`+ const response = await this.request(path, undefined, signal, 'DELETE', { 'X-Boxlite-Organization-Id': orgId })+ await response.body?.cancel()+ if (response.status !== 204) throw new Error('Secret retirement failed')+ })+ }+ validateInline(secrets: BoxSecret[]): void {if (secrets.length > 64) throw new BadRequestError('secrets must contain at most 64 entries')// Match the write contract's ASCII name normalization before any remote side effect.const names = new Set<string>()for (const [index, { name, value, placeholder }] of secrets.entries()) {- const normalized = name.replace(/[a-z]/g, (letter) => letter.toUpperCase()).replace(/[^A-Z0-9_]/gu, '_')+ const normalized = normalizedName(name)if (normalized.length < 1 || normalized.length > 64) {throw new BadRequestError(`secrets[${index}].name must normalize to 1–64 characters`)}@@ -43,8 +74,30 @@ export class SecretServerClient {if (names.has(normalized)) throw new BadRequestError('Secret names must be unique after normalization')names.add(normalized)}+ }++ async storeBoxSecrets(+ boxId: string,+ orgId: string,+ createdBy: string | undefined,+ secrets: BoxSecret[],+ ): Promise<BoxSecret[]> {+ if (!this.config.get('secretServer.enabled') || secrets.length === 0) return secrets++ this.validateInline(secrets)const started = Date.now()+ let result = 'failure'+ try {+ const references = await this.withDeadline((signal) => this.transfer(boxId, orgId, createdBy, secrets, signal))+ result = 'success'+ return references+ } finally {+ this.logger.log({ boxId, count: secrets.length, result, latencyMs: Date.now() - started })+ }+ }++ private async withDeadline<T>(operation: (signal: AbortSignal) => Promise<T>): Promise<T> {const controller = new AbortController()let timer: ReturnType<typeof setTimeout>const deadline = new Promise<never>((_, reject) => {@@ -53,31 +106,170 @@ export class SecretServerClient {reject(new Error('Secret transfer deadline exceeded'))}, TRANSFER_TIMEOUT_MS)})- let result = 'failure'try {- const references = await Promise.race([- this.transfer(boxId, orgId, createdBy, secrets, controller.signal),- deadline,- ])- result = 'success'- return references- } catch {- // Auth/HTTP errors can retain request bodies or echo secret material.+ return await Promise.race([operation(controller.signal), deadline])+ } catch (error) {+ if (error instanceof SecretResponseError) {+ if (error.status === 409) throw new ConflictException('Secret name is already in use')+ if (error.status === 404) throw new NotFoundException('Secret not found')+ if (error.status === 422) throw new BadRequestException('Invalid organization secret')+ }throw new ServiceUnavailableException({ code: 'secret_store_unavailable', message: 'Secret store unavailable' })} finally {clearTimeout(timer)- this.logger.log({ boxId, count: secrets.length, result, latencyMs: Date.now() - started })}}- private async transfer(- boxId: string,+ private async organizationRequest(orgId: string,- createdBy: string | undefined,- secrets: BoxSecret[],+ suffix: string,+ method: 'POST' | 'GET' | 'HEAD' | 'DELETE',+ status: number,+ payload?: unknown,+ ): Promise<unknown> {+ if (!this.config.get('secretServer.enabled')) throw new ServiceUnavailableException('Secret store unavailable')+ return this.withDeadline(async (signal) => {+ const path = `/internal/v1/organizations/${encodeURIComponent(orgId)}/secrets${suffix}`+ const response = await this.request(path, payload, signal, method)+ if (response.status !== status) {+ await response.body?.cancel()+ throw new SecretResponseError(response.status)+ }+ if (status !== 204) return response.json()+ })+ }++ async createOrganizationSecret(+ orgId: string,+ creator: string,+ secret: BoxSecret,+ ): Promise<OrganizationSecretIdentity> {+ const body = await this.organizationRequest(orgId, '', 'POST', 201, {+ created_by: creator,+ secret: {+ name: secret.name,+ value: secret.value,+ hosts: secret.hosts,+ headers: secret.headers,+ placeholder: secret.placeholder ?? `<BOXLITE_SECRET:${secret.name}>`,+ },+ })+ if (+ !body ||+ typeof body !== 'object' ||+ !('id' in body) ||+ typeof body.id !== 'string' ||+ !UUID.test(body.id) ||+ !('name' in body) ||+ body.name !== secret.name+ )+ throw new ServiceUnavailableException('Invalid secret store response')+ return { id: body.id, name: secret.name }+ }++ async listOrganizationSecrets(+ org: string,+ after: string | undefined,+ limit: number,+ ): Promise<OrganizationSecretListItem[]> {+ const query = new URLSearchParams({ limit: String(limit) })+ if (after) query.set('after', after)+ const body = await this.organizationRequest(org, '?' + query.toString(), 'GET', 200)+ if (+ !body ||+ typeof body !== 'object' ||+ !('secrets' in body) ||+ !Array.isArray(body.secrets) ||+ body.secrets.length > limit+ )+ throw new ServiceUnavailableException('Invalid secret store response')+ return body.secrets.map((item) => {+ if (+ !item ||+ typeof item.id !== 'string' ||+ !UUID.test(item.id) ||+ typeof item.name !== 'string' ||+ !item.name ||+ !Array.isArray(item.hosts) ||+ !item.hosts.every((host: unknown) => typeof host === 'string') ||+ !item.headers ||+ typeof item.headers !== 'object' ||+ Array.isArray(item.headers) ||+ !Object.values(item.headers).every((template) => typeof template === 'string') ||+ typeof item.placeholder !== 'string'+ )+ throw new ServiceUnavailableException('Invalid secret store response')+ const { id, name, hosts, headers, placeholder } = item+ return { id, name, hosts, headers, placeholder }+ })+ }++ async checkOrganizationSecret(org: string, id: string): Promise<void> {+ await this.organizationRequest(org, '/' + encodeURIComponent(id), 'HEAD', 204)+ }++ async deleteOrganizationSecret(org: string, id: string): Promise<void> {+ await this.organizationRequest(org, '/' + encodeURIComponent(id), 'DELETE', 204)+ }++ async resolveForBox(orgId: string, entries: (BoxSecret | NamedSecret)[]): Promise<BoxSecret[]> {+ if (entries.some((entry) => 'secretId' in entry)) throw new BadRequestError('Secret IDs are server-assigned')+ const names = entries.filter((entry): entry is NamedSecret => 'secret' in entry)+ if (!names.length) return entries as BoxSecret[]+ if (entries.length > 64) throw new BadRequestError('secrets must contain at most 64 entries')+ if (names.some((entry) => typeof entry.secret !== 'string' || Object.keys(entry).length !== 1))+ throw new BadRequestError('A named secret accepts only a name')+ const keys = entries.map((entry) => normalizedName('secret' in entry ? entry.secret : entry.name))+ if (keys.some((key) => !key || key.length > 64) || new Set(keys).size !== keys.length)+ throw new BadRequestError('Invalid or duplicate secret names')+ const body = await this.organizationRequest(orgId, '/resolve', 'POST', 200, {+ names: names.map((entry) => entry.secret),+ })+ if (+ !body ||+ typeof body !== 'object' ||+ !('secrets' in body) ||+ !Array.isArray(body.secrets) ||+ body.secrets.length !== names.length+ )+ throw new ServiceUnavailableException('Invalid secret store response')+ const resolved = new Map<string, BoxSecret>()+ const ids = new Set<string>()+ for (const [i, item] of body.secrets.entries()) {+ if (+ !item ||+ typeof item.name !== 'string' ||+ normalizedName(item.name) !== normalizedName(names[i].secret) ||+ typeof item.id !== 'string' ||+ !UUID.test(item.id) ||+ ids.has(item.id.toLowerCase()) ||+ !Array.isArray(item.hosts) ||+ !item.hosts.every((host: unknown) => typeof host === 'string' && host) ||+ typeof item.placeholder !== 'string' ||+ !item.placeholder ||+ !item.headers ||+ typeof item.headers !== 'object'+ )+ throw new ServiceUnavailableException('Invalid secret store response')+ ids.add(item.id.toLowerCase())+ resolved.set(names[i].secret, {+ name: item.name,+ secretId: item.id,+ hosts: item.hosts,+ headers: item.headers,+ placeholder: item.placeholder,+ })+ }+ return entries.map((entry) => ('secret' in entry ? resolved.get(entry.secret)! : entry))+ }++ private async request(+ path: string,+ payload: unknown,signal: AbortSignal,- ): Promise<BoxSecret[]> {- if (!createdBy) throw new Error('Creator identity required')+ method = 'POST',+ headers: Record<string, string> = {},+ ): Promise<Response> {const url = this.config.get('secretServer.url')const devToken = this.config.get('secretServer.devToken')const authorization = devToken@@ -86,6 +278,23 @@ export class SecretServerClient {// Identity acquisition cannot be cancelled by the library. Never start a late POST.signal.throwIfAborted()if (!authorization) throw new Error('Caller identity unavailable')+ return fetch(url + path, {+ method,+ headers: { authorization, 'content-type': 'application/json', ...headers },+ body: JSON.stringify(payload),+ redirect: 'error',+ signal,+ })+ }++ private async transfer(+ boxId: string,+ orgId: string,+ createdBy: string | undefined,+ secrets: BoxSecret[],+ signal: AbortSignal,+ ): Promise<BoxSecret[]> {+ if (!createdBy) throw new Error('Creator identity required')const payload = secrets.map(({ name, value, hosts, headers, placeholder }) => ({name,value,@@ -93,13 +302,15 @@ export class SecretServerClient {headers,placeholder: placeholder ?? `<BOXLITE_SECRET:${name}>`,}))- const response = await fetch(`${url}/internal/v1/boxes/${encodeURIComponent(boxId)}/secrets`, {- method: 'POST',- headers: { authorization, 'content-type': 'application/json' },- body: JSON.stringify({ org_id: orgId, created_by: createdBy, secrets: payload }),- redirect: 'error',+ const response = await this.request(+ `/internal/v1/boxes/${encodeURIComponent(boxId)}/secrets`,+ {+ org_id: orgId,+ created_by: createdBy,+ secrets: payload,+ },signal,- })+ )if (response.status !== 200 && response.status !== 201) {await response.body?.cancel()throw new Error('Secret transfer rejected')diff --git a/apps/api/src/boxlite-rest/admin-api.spec.ts b/apps/api/src/boxlite-rest/admin-api.spec.tsindex e19b6ebff..4ca98a0e8 100644--- a/apps/api/src/boxlite-rest/admin-api.spec.ts+++ b/apps/api/src/boxlite-rest/admin-api.spec.ts@@ -262,6 +262,9 @@ describe('Admin API HTTP contract', () => {expect((await call('POST', '/organizations/invites', payload, { 'Idempotency-Key': 'invalid' })).status).toBe(400)expect(invites.create).not.toHaveBeenCalled()})+ it.each(['/organizations/users', '/organizations/invites'])('accepts pageSize 1000 for %s', async (path) => {+ expect((await call('GET', path + '?pageSize=1000')).status).toBe(200)+ })it.each(['0', '1001', '1.5', 'bad'])('rejects pageSize %s', async (size) => {expect((await call('GET', `/organizations/users?pageSize=${size}`)).status).toBe(400)expect(members.findPage).not.toHaveBeenCalled()diff --git a/apps/api/src/boxlite-rest/boxlite-box.controller.ts b/apps/api/src/boxlite-rest/boxlite-box.controller.tsindex 1b1e66a9d..a93e21898 100644--- a/apps/api/src/boxlite-rest/boxlite-box.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-box.controller.ts@@ -119,11 +119,11 @@ export class BoxliteBoxController {env: req.body?.env? Object.fromEntries(Object.keys(req.body?.env).map((key) => [key, MASKED_AUDIT_VALUE])): undefined,- secrets: req.body?.secrets?.map((s) => ({- name: s.name,- hosts: s.hosts,- value: MASKED_AUDIT_VALUE,- })),+ secrets: req.body?.secrets?.map((entry) => {+ if (!entry || typeof entry !== 'object') return {}+ if ('secret' in entry) return { secret: typeof entry.secret === 'string' ? entry.secret : undefined }+ return { name: entry.name, hosts: entry.hosts, value: MASKED_AUDIT_VALUE }+ }),cpus: req.body?.cpus,memory_mib: req.body?.memory_mib,disk_size_gb: req.body?.disk_size_gb,diff --git a/apps/api/src/boxlite-rest/boxlite-rest.module.ts b/apps/api/src/boxlite-rest/boxlite-rest.module.tsindex 2295d675c..6160dc7b9 100644--- a/apps/api/src/boxlite-rest/boxlite-rest.module.ts+++ b/apps/api/src/boxlite-rest/boxlite-rest.module.ts@@ -32,6 +32,7 @@ import { BoxliteWsProxyService } from './boxlite-ws-proxy.service'import { BoxliteVolumeController } from './boxlite-volume.controller'import { BoxliteImageController } from './boxlite-image.controller'import { ImageModule } from '../image/image.module'+import { BoxliteSecretController } from './boxlite-secret.controller'import { BoxliteRegistryController } from './boxlite-registry.controller'import { RegistryModule } from '../registry/registry.module'import { BoxliteMemberController } from './boxlite-member.controller'@@ -69,6 +70,7 @@ import { BoxReadinessInterceptor } from '../box/interceptors/box-readiness.interBoxliteBoxController,BoxliteProxyController,BoxliteVolumeController,+ BoxliteSecretController,BoxliteRegistryController,BoxliteImageController,BoxliteMemberController,diff --git a/apps/api/src/boxlite-rest/boxlite-secret.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-secret.controller.spec.tsnew file mode 100644index 000000000..a9649f934--- /dev/null+++ b/apps/api/src/boxlite-rest/boxlite-secret.controller.spec.ts@@ -0,0 +1,238 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */++import { INestApplication } from '@nestjs/common'+import { getRedisConnectionToken } from '@nestjs-modules/ioredis'+import { Test } from '@nestjs/testing'+import { randomUUID } from 'node:crypto'+import { CombinedAuthGuard } from '../auth/combined-auth.guard'+import { OrgSecretRetirementService } from '../box/services/org-secret-retirement.service'+import { SecretServerClient } from '../box/services/secret-server-client'+import { AuthenticatedRateLimitGuard } from '../common/guards/authenticated-rate-limit.guard'+import { TypedConfigService } from '../config/typed-config.service'+import { OrganizationService } from '../organization/services/organization.service'+import { OrganizationUserService } from '../organization/services/organization-user.service'+import { BoxliteSecretController } from './boxlite-secret.controller'++describe('/api/v1/secrets', () => {+ let app: INestApplication+ let permissions: string[]+ const store = { createOrganizationSecret: jest.fn(), listOrganizationSecrets: jest.fn() }+ const retirements = { remove: jest.fn() }+ let organizationId: string+ const input = {+ name: 'openai',+ value: 'synthetic',+ hosts: ['upstream.example'],+ headers: { Authorization: 'Bearer {value}' },+ }+ async function startApi(+ secretStore: Pick<SecretServerClient, 'createOrganizationSecret' | 'listOrganizationSecrets'>,+ ) {+ const module = await Test.createTestingModule({+ controllers: [BoxliteSecretController],+ providers: [+ { provide: OrgSecretRetirementService, useValue: retirements },+ { provide: SecretServerClient, useValue: secretStore },+ {+ provide: OrganizationService,+ useValue: { findOne: async (id: string) => ({ id }), assertOrganizationIsNotSuspended: jest.fn() },+ },+ { provide: OrganizationUserService, useValue: { findOneCached: async () => ({ role: 'owner' }) } },+ { provide: getRedisConnectionToken(), useValue: { get: async () => null, set: async () => 'OK' } },+ ],+ })+ .overrideGuard(CombinedAuthGuard)+ .useValue({+ canActivate(ctx) {+ ctx.switchToHttp().getRequest().user = {+ userId: 'creator',+ role: 'user',+ organizationId,+ apiKey: { organizationId, permissions },+ }+ return true+ },+ })+ .overrideGuard(AuthenticatedRateLimitGuard)+ .useValue({ canActivate: () => true })+ .compile()+ const api = module.createNestApplication()+ api.setGlobalPrefix('api')+ await api.listen(0, '127.0.0.1')+ return api+ }+ beforeAll(async () => {+ app = await startApi(store)+ })+ beforeEach(() => {+ organizationId = 'org-a'+ jest.clearAllMocks()+ })+ afterAll(async () => app?.close())+ async function create(body: unknown, api = app) {+ return fetch((await api.getUrl()) + '/api/v1/secrets', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ })+ }+ it('derives the organization and creator from identity and enforces the key scope', async () => {+ permissions = ['write:boxes']+ expect((await create(input)).status).toBe(403)+ expect(store.createOrganizationSecret).not.toHaveBeenCalled()+ permissions = ['write:secrets']+ expect((await create({ ...input, organization_id: 'org-b' })).status).toBe(400)+ expect(store.createOrganizationSecret).not.toHaveBeenCalled()+ const identity = { id: '1dd00103-6203-450a-86cc-ab12456eca34', name: input.name }+ store.createOrganizationSecret.mockResolvedValue(identity)+ const response = await create(input)+ expect(response.status).toBe(201)+ expect(await response.json()).toEqual(identity)+ expect(store.createOrganizationSecret).toHaveBeenCalledWith('org-a', 'creator', input)+ })++ const live = process.env.SECRET_SERVER_URL && process.env.SECRET_SERVER_DEV_TOKEN ? it : it.skip+ function liveClient() {+ const config = {+ 'secretServer.enabled': true,+ 'secretServer.url': process.env.SECRET_SERVER_URL,+ 'secretServer.devToken': process.env.SECRET_SERVER_DEV_TOKEN,+ }+ return new SecretServerClient({ get: (key: string) => config[key] } as TypedConfigService)+ }+ live('lists stored routing metadata through the public API for only the caller’s organization secrets', async () => {+ const client = liveClient()+ const api = await startApi(client)+ const owner = randomUUID()+ const foreign = randomUUID()+ const boxId = randomUUID().replaceAll('-', '').slice(0, 12)+ const policy = {+ hosts: ['second.example', 'first.example'],+ headers: { Authorization: 'Bearer {value}', 'X-Service-Key': 'prefix-{value}' },+ placeholder: 'custom-list-marker',+ }+ permissions = ['read:secrets', 'write:secrets']+ const value = randomUUID()+ const secret = { name: 'openai', value, ...policy }+ const created = new Map<string, string>()+ try {+ for (const org of [owner, foreign]) {+ organizationId = org+ const response = await create(secret, api)+ expect(response.status).toBe(201)+ const identity = await response.json()+ created.set(org, identity.id)+ expect(identity).toEqual({ id: expect.any(String), name: secret.name })+ }+ expect(created.get(owner)).not.toBe(created.get(foreign))+ const [privateRef] = await client.storeBoxSecrets(boxId, owner, 'creator', [{ ...secret, name: 'private' }])+ expect(privateRef.secretId).toEqual(expect.any(String))+ for (const org of [owner, foreign]) {+ organizationId = org+ const response = await fetch((await api.getUrl()) + '/api/v1/secrets')+ expect(response.status).toBe(200)+ const body = await response.text()+ expect(body).not.toContain(value)+ expect(JSON.parse(body)).toEqual({ secrets: [{ id: created.get(org), name: secret.name, ...policy }] })+ }+ } finally {+ try {+ await client.retireBoxSecrets(owner, boxId)+ for (const [org, id] of created) await client.deleteOrganizationSecret(org, id)+ } finally {+ await api.close()+ }+ }+ })++ live(+ 'returns all 101 organization secrets in default pages of 100 and 1',+ async () => {+ const client = liveClient()+ const api = await startApi(client)+ const org = randomUUID()+ organizationId = org+ permissions = ['read:secrets', 'write:secrets']+ const ids: string[] = []+ try {+ for (let i = 0; i < 101; i++) {+ const response = await create({ ...input, name: 'key-' + i }, api)+ expect(response.status).toBe(201)+ ids.push((await response.json()).id)+ }+ const url = (await api.getUrl()) + '/api/v1/secrets'+ const first = await fetch(url)+ expect(first.status).toBe(200)+ const page = await first.json()+ expect(page.secrets).toHaveLength(100)+ expect(page.next_page_token).toEqual(expect.any(String))+ const next = await fetch(url + '?pageToken=' + encodeURIComponent(page.next_page_token))+ expect(next.status).toBe(200)+ const last = await next.json()+ expect(last.secrets).toHaveLength(1)+ expect(last).not.toHaveProperty('next_page_token')+ expect([...page.secrets, ...last.secrets].map((row) => row.id)).toEqual(ids.sort())+ } finally {+ try {+ for (const id of ids) await client.deleteOrganizationSecret(org, id)+ } finally {+ await api.close()+ }+ }+ },+ 30_000,+ )++ it('rejects pageSize 101 and asks the store for 101 rows for pageSize 100', async () => {+ permissions = ['read:secrets']+ store.listOrganizationSecrets.mockResolvedValue([])+ const url = (await app.getUrl()) + '/api/v1/secrets'+ expect((await fetch(url + '?pageSize=101')).status).toBe(400)+ expect(store.listOrganizationSecrets).not.toHaveBeenCalled()+ expect((await fetch(url + '?pageSize=100')).status).toBe(200)+ expect(store.listOrganizationSecrets).toHaveBeenCalledWith('org-a', undefined, 101)+ })++ it('paginates secret metadata and binds the token to the authenticated organization', async () => {+ const url = (await app.getUrl()) + '/api/v1/secrets'+ permissions = ['write:secrets']+ expect((await fetch(url)).status).toBe(403)+ expect(store.listOrganizationSecrets).not.toHaveBeenCalled()+ permissions = ['read:secrets']+ const policy = { hosts: input.hosts, headers: input.headers, placeholder: 'custom' }+ const one = { id: '10000000-0000-4000-8000-000000000001', name: 'first', ...policy }+ const two = { id: '20000000-0000-4000-8000-000000000002', name: 'second', ...policy }+ store.listOrganizationSecrets.mockResolvedValueOnce([one, two]).mockResolvedValueOnce([two])+ const first = await fetch(url + '?pageSize=1')+ expect(first.status).toBe(200)+ expect(first.headers.get('cache-control')).toBe('no-store')+ const page = await first.json()+ expect(page).toEqual({ secrets: [one], next_page_token: expect.any(String) })+ const next = url + '?pageSize=1&pageToken=' + encodeURIComponent(page.next_page_token)+ expect(await (await fetch(next)).json()).toEqual({ secrets: [two] })+ expect(store.listOrganizationSecrets.mock.calls).toEqual([+ ['org-a', undefined, 2],+ ['org-a', one.id, 2],+ ])+ organizationId = 'org-b'+ expect((await fetch(next)).status).toBe(400)+ for (const query of ['pageSize=0', 'pageSize=1.5', 'pageSize=x', 'pageToken=x', 'organization_id=org-a']) {+ expect((await fetch(url + '?' + query)).status).toBe(400)+ }+ expect(store.listOrganizationSecrets).toHaveBeenCalledTimes(2)+ })++ it('requires write permission and a UUID for deletion', async () => {+ const url = (await app.getUrl()) + '/api/v1/secrets/'+ const id = '1dd00103-6203-450a-86cc-ab12456eca34'+ permissions = ['read:secrets']+ expect((await fetch(url + id, { method: 'DELETE' })).status).toBe(403)+ permissions = ['write:secrets']+ expect((await fetch(url + 'openai', { method: 'DELETE' })).status).toBe(400)+ expect(retirements.remove).not.toHaveBeenCalled()+ const response = await fetch(url + id, { method: 'DELETE' })+ expect(response.status).toBe(204)+ expect(await response.text()).toBe('')+ expect(retirements.remove).toHaveBeenCalledWith('org-a', id)+ })+})diff --git a/apps/api/src/boxlite-rest/boxlite-secret.controller.ts b/apps/api/src/boxlite-rest/boxlite-secret.controller.tsnew file mode 100644index 000000000..2c7b69c13--- /dev/null+++ b/apps/api/src/boxlite-rest/boxlite-secret.controller.ts@@ -0,0 +1,92 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */++import {+ Body,+ Controller,+ Delete,+ ForbiddenException,+ Get,+ Header,+ HttpCode,+ Param,+ ParseUUIDPipe,+ Post,+ Query,+ UseGuards,+ UsePipes,+} from '@nestjs/common'+import { ApiExcludeController } from '@nestjs/swagger'+import { Audit, TypedRequest } from '../audit/decorators/audit.decorator'+import { AuditAction } from '../audit/enums/audit-action.enum'+import { AuditTarget } from '../audit/enums/audit-target.enum'+import { CombinedAuthGuard } from '../auth/combined-auth.guard'+import { validateSecrets } from '../box/services/box.service'+import { OrgSecretRetirementService } from '../box/services/org-secret-retirement.service'+import { SecretServerClient } from '../box/services/secret-server-client'+import { AuthContext } from '../common/decorators/auth-context.decorator'+import { AuthenticatedRateLimitGuard } from '../common/guards/authenticated-rate-limit.guard'+import { OrganizationAuthContext } from '../common/interfaces/auth-context.interface'+import { ReplayValidationPipe } from '../common/replay-validation.pipe'+import { RequiredOrganizationResourcePermissions } from '../organization/decorators/required-organization-resource-permissions.decorator'+import { OrganizationResourcePermission } from '../organization/enums/organization-resource-permission.enum'+import { OrganizationResourceActionGuard } from '../organization/guards/organization-resource-action.guard'+import { OrganizationService } from '../organization/services/organization.service'+import { SecretPageQuery, adminNextPage } from './dto/admin-page-query.dto'+import { SecretSpecDto } from './dto/create-box.dto'++@Controller('v1/secrets')+@ApiExcludeController()+@UseGuards(CombinedAuthGuard, OrganizationResourceActionGuard, AuthenticatedRateLimitGuard)+@UsePipes(new ReplayValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))+export class BoxliteSecretController {+ constructor(+ private readonly store: SecretServerClient,+ private readonly retirements: OrgSecretRetirementService,+ private readonly organizations: OrganizationService,+ ) {}++ @Post()+ @RequiredOrganizationResourcePermissions([OrganizationResourcePermission.WRITE_SECRETS])+ @Audit({+ action: AuditAction.CREATE,+ targetType: AuditTarget.SECRET,+ targetIdFromResult: (result: { id: string }) => result.id,+ requestMetadata: { body: (req: TypedRequest<SecretSpecDto>) => ({ name: req.body?.name }) },+ })+ async create(@AuthContext() auth: OrganizationAuthContext, @Body() secret: SecretSpecDto) {+ const org = this.organizationId(auth)+ validateSecrets([secret])+ return this.store.createOrganizationSecret(org, auth.userId, secret)+ }++ @Get()+ @Header('Cache-Control', 'no-store')+ @RequiredOrganizationResourcePermissions([OrganizationResourcePermission.READ_SECRETS])+ async list(@AuthContext() auth: OrganizationAuthContext, @Query() page: SecretPageQuery) {+ const org = this.organizationId(auth)+ const rows = await this.store.listOrganizationSecrets(org, page.after(org, 'secrets'), page.pageSize + 1)+ return {+ secrets: rows.slice(0, page.pageSize),+ ...adminNextPage(rows, page.pageSize, org, 'secrets', (row) => row.id),+ }+ }++ @Delete(':secretId')+ @HttpCode(204)+ @RequiredOrganizationResourcePermissions([OrganizationResourcePermission.WRITE_SECRETS])+ @Audit({+ action: AuditAction.DELETE,+ targetType: AuditTarget.SECRET,+ targetIdFromRequest: (req) => req.params.secretId,+ })+ async remove(@AuthContext() auth: OrganizationAuthContext, @Param('secretId', ParseUUIDPipe) id: string) {+ await this.retirements.remove(this.organizationId(auth), id.toLowerCase())+ }++ private organizationId(auth: OrganizationAuthContext): string {+ if (!auth.organizationId || auth.organization?.id !== auth.organizationId)+ throw new ForbiddenException('Organization identity required')+ this.organizations.assertOrganizationIsNotSuspended(auth.organization)+ return auth.organizationId+ }+}diff --git a/apps/api/src/boxlite-rest/dto/admin-page-query.dto.ts b/apps/api/src/boxlite-rest/dto/admin-page-query.dto.tsindex d2736e7c2..9cb3c8dba 100644--- a/apps/api/src/boxlite-rest/dto/admin-page-query.dto.ts+++ b/apps/api/src/boxlite-rest/dto/admin-page-query.dto.ts@@ -3,18 +3,24 @@* SPDX-License-Identifier: AGPL-3.0*/-import { BadRequestException } from '@nestjs/common'+import { applyDecorators, BadRequestException } from '@nestjs/common'import { Type } from 'class-transformer'import { IsInt, IsString, Length, Max, Min, ValidateIf, isUUID } from 'class-validator'import { cursorFor, cursorValue } from '../../admin/utils/pagination'-type Resource = 'users' | 'invites'+type Resource = 'users' | 'invites' | 'secrets'++function PageSize(maximum: number) {+ return applyDecorators(+ Type(() => Number),+ IsInt(),+ Min(1),+ Max(maximum),+ )+}export class AdminPageQuery {- @Type(() => Number)- @IsInt()- @Min(1)- @Max(1000)+ @PageSize(1000)pageSize = 100@ValidateIf((_object, value) => value !== undefined)@@ -34,7 +40,7 @@ export class AdminPageQuery {cursor[2] !== resource ||typeof cursor[3] !== 'string' ||!cursor[3] ||- (resource === 'invites' && !isUUID(cursor[3]))+ (resource !== 'users' && !isUUID(cursor[3]))) {throw new Error('Invalid page token')}@@ -45,6 +51,11 @@ export class AdminPageQuery {}}+export class SecretPageQuery extends AdminPageQuery {+ @PageSize(100)+ declare pageSize: number+}+export function adminNextPage<T>(rows: T[],size: number,diff --git a/apps/api/src/boxlite-rest/dto/create-box.dto.spec.ts b/apps/api/src/boxlite-rest/dto/create-box.dto.spec.tsindex f46c56478..7f6774991 100644--- a/apps/api/src/boxlite-rest/dto/create-box.dto.spec.ts+++ b/apps/api/src/boxlite-rest/dto/create-box.dto.spec.ts@@ -456,6 +456,22 @@ describe('CreateBoxDto detach policy', () => {})describe('CreateBoxDto secrets', () => {+ it('accepts mixed named and inline entries and rejects reference overrides', async () => {+ const inline = { name: 'private', value: 'fixture', hosts: ['private.example'], headers: { 'X-Auth': '{value}' } }+ const options = { whitelist: true, forbidNonWhitelisted: true }+ expect(+ await validate(plainToInstance(CreateBoxDto, { secrets: [inline, { secret: 'openai' }] }), options),+ ).toHaveLength(0)+ for (const reference of [+ { secret: 'openai', hosts: inline.hosts },+ { secret: 'openai', value: inline.value },+ { secret: '' },+ { secretId: 'id' },+ ]) {+ expect(await validate(plainToInstance(CreateBoxDto, { secrets: [reference] }), options)).not.toHaveLength(0)+ }+ })+it('accepts a secret with name+value+hosts and an optional placeholder', async () => {const errors = await validate(plainToInstance(CreateBoxDto, {diff --git a/apps/api/src/boxlite-rest/dto/create-box.dto.ts b/apps/api/src/boxlite-rest/dto/create-box.dto.tsindex fc07e69a1..b2aa795f3 100644--- a/apps/api/src/boxlite-rest/dto/create-box.dto.ts+++ b/apps/api/src/boxlite-rest/dto/create-box.dto.ts@@ -217,6 +217,12 @@ export class VolumeSpecDto {read_only?: false}+export class NamedSecretDto {+ @IsString()+ @IsNotEmpty()+ secret: string+}+export class SecretSpecDto {@IsString()@IsNotEmpty()@@ -339,8 +345,18 @@ export class CreateBoxDto {@IsOptional()@IsArray()@ValidateNested({ each: true })- @Type(() => SecretSpecDto)- secrets?: SecretSpecDto[]+ @Transform(+ ({ value }) =>+ Array.isArray(value)+ ? value.map((item) =>+ item && typeof item === 'object' && 'secret' in item+ ? plainToInstance(NamedSecretDto, item)+ : plainToInstance(SecretSpecDto, item),+ )+ : value,+ { toClassOnly: true },+ )+ secrets?: (SecretSpecDto | NamedSecretDto)[]// The remaining CreateBoxRequest fields this server does not implement.// Without these, whitelisting reports them as a bare "property X should notdiff --git a/apps/api/src/boxlite-rest/mappers/box-to-box.mapper.ts b/apps/api/src/boxlite-rest/mappers/box-to-box.mapper.tsindex 72ce14f33..28f216e87 100644--- a/apps/api/src/boxlite-rest/mappers/box-to-box.mapper.ts+++ b/apps/api/src/boxlite-rest/mappers/box-to-box.mapper.ts@@ -69,13 +69,17 @@ export function createBoxToCreateBox(dto: RestCreateBoxDto, target?: string): CrvolumeId: volume.managed_volume,mountPath: volume.guest_path,}))- createDto.secrets = dto.secrets?.map((secret) => ({- name: secret.name,- value: secret.value,- hosts: secret.hosts,- placeholder: secret.placeholder,- headers: secret.headers,- }))+ createDto.secrets = dto.secrets?.map((secret) =>+ 'secret' in secret+ ? { secret: secret.secret }+ : {+ name: secret.name,+ value: secret.value,+ hosts: secret.hosts,+ placeholder: secret.placeholder,+ headers: secret.headers,+ },+ )// Only an explicit inbound.mode=enabled enables inbound access. Omitting// inbound (including the legacy flat network shape) leaves it disabled.createDto.inboundEnabled = dto.network?.inbound?.mode === 'enabled'diff --git a/apps/api/src/config/secret-server-config.ts b/apps/api/src/config/secret-server-config.tsindex b72a60bc6..2a5c6bd96 100644--- a/apps/api/src/config/secret-server-config.ts+++ b/apps/api/src/config/secret-server-config.ts@@ -30,5 +30,9 @@ export function secretServerConfig(env: NodeJS.ProcessEnv = process.env): {}const devToken = env.SECRET_SERVER_DEV_TOKEN?.trim() || undefinedif (devToken && !local) throw new Error('SECRET_SERVER_DEV_TOKEN is only allowed in local/dev')- return { enabled, url: raw.replace(/\/+$/, ''), devToken }+ return {+ enabled,+ url: raw.replace(/\/+$/, ''),+ devToken,+ }}diff --git a/apps/api/src/mcp/mcp-tools.spec.ts b/apps/api/src/mcp/mcp-tools.spec.tsindex 6884ce16a..8a28849f1 100644--- a/apps/api/src/mcp/mcp-tools.spec.ts+++ b/apps/api/src/mcp/mcp-tools.spec.ts@@ -228,6 +228,9 @@ const API_KEY_ONLY = ['listRegistries','createRegistry','removeRegistry',+ 'listOrganizationSecrets',+ 'createOrganizationSecret',+ 'deleteOrganizationSecret','listUsers','removeUser','listInvites',diff --git a/apps/api/src/migrations/pre-deploy/1792497600000-add-tenant-scopes-migration.integration.spec.ts b/apps/api/src/migrations/pre-deploy/1792497600000-add-tenant-scopes-migration.integration.spec.tsindex 55980ddd7..9a979fb3e 100644--- a/apps/api/src/migrations/pre-deploy/1792497600000-add-tenant-scopes-migration.integration.spec.ts+++ b/apps/api/src/migrations/pre-deploy/1792497600000-add-tenant-scopes-migration.integration.spec.ts@@ -6,6 +6,9 @@ import { AddImageCatalogApi1787400000000 } from './1787400000000-add-image-catalimport { AddRegistryReadScope1790500000000 } from './1790500000000-add-registry-read-scope-migration'import { AddImageWriteScope1790700000000 } from './1790700000000-add-image-write-scope-migration'import { RenameMemberScopes1792728000000 } from './1792728000000-rename-member-scopes-migration'+import { AddCloudAppScopes1793780000000 } from './1793780000000-add-cloud-app-scopes-migration'+import { AddSecretScope1795996800000 } from './1795996800000-add-secret-scope-migration'+import { AddSecretReadScope1796169600001 } from './1796169600001-add-secret-read-scope-migration'import { AddTenantScopes1792497600000 } from './1792497600000-add-tenant-scopes-migration'const describeIfDatabase = process.env.DB_HOST ? describe : describe.skip@@ -163,6 +166,43 @@ describeIfDatabase('AddTenantScopes1792497600000 (integration, real Postgres)',}})+ it('upgrades write-only secret grants and rolls back read without removing write', async () => {+ await migrate('up')+ await new RenameMemberScopes1792728000000().up(queryRunner)+ await new AddCloudAppScopes1793780000000().up(queryRunner)+ const appScopes = ['read:apps', 'write:apps', 'delete:apps']+ await seed('app-manager', appScopes)+ const write = new AddSecretScope1795996800000()+ const read = new AddSecretReadScope1796169600001()+ await write.up(queryRunner)+ await seed('writer', ['write:secrets'])+ await read.up(queryRunner)+ await seed('both', ['read:secrets', 'write:secrets'])+ for (const table of tables) {+ expect(await grants(table)).toContainEqual({ name: 'writer', permissions: ['write:secrets'] })+ expect(await scopes(table)).toEqual([+ ...scopesBefore,+ 'read:members',+ 'write:members',+ ...appScopes,+ 'write:secrets',+ 'read:secrets',+ ])+ }+ await read.down(queryRunner)+ for (const table of tables) {+ expect(await grants(table)).toContainEqual({ name: 'both', permissions: ['write:secrets'] })+ expect(await grants(table)).toContainEqual({ name: 'app-manager', permissions: appScopes })+ expect(await scopes(table)).not.toContain('read:secrets')+ }+ await write.down(queryRunner)+ for (const table of tables) {+ expect(await grants(table)).toContainEqual({ name: 'writer', permissions: [] })+ expect(await grants(table)).toContainEqual({ name: 'app-manager', permissions: appScopes })+ expect(await scopes(table)).toEqual([...scopesBefore, 'read:members', 'write:members', ...appScopes])+ }+ })+it('rolls back both enums, removing only tenant grants and retaining old scope order', async () => {await migrate('up')await seed('mixed', ['read:tenant', ...scopesBefore, 'write:tenant'])diff --git a/apps/api/src/migrations/pre-deploy/1795996800000-add-secret-scope-migration.ts b/apps/api/src/migrations/pre-deploy/1795996800000-add-secret-scope-migration.tsnew file mode 100644index 000000000..2c34995e5--- /dev/null+++ b/apps/api/src/migrations/pre-deploy/1795996800000-add-secret-scope-migration.ts@@ -0,0 +1,14 @@+import { MigrationInterface, QueryRunner } from 'typeorm'+import { addSecretScope, removeSecretScope } from '../secret-permission-scopes'++export class AddSecretScope1795996800000 implements MigrationInterface {+ name = 'AddSecretScope1795996800000'++ up(runner: QueryRunner): Promise<void> {+ return addSecretScope(runner, 'write:secrets')+ }++ down(runner: QueryRunner): Promise<void> {+ return removeSecretScope(runner, 'write:secrets')+ }+}diff --git a/apps/api/src/migrations/pre-deploy/1796083200000-box-secret-cleanup-migration.ts b/apps/api/src/migrations/pre-deploy/1796083200000-box-secret-cleanup-migration.tsnew file mode 100644index 000000000..bbd2c5713--- /dev/null+++ b/apps/api/src/migrations/pre-deploy/1796083200000-box-secret-cleanup-migration.ts@@ -0,0 +1,38 @@+import { MigrationInterface, QueryRunner } from 'typeorm'++export class BoxSecretCleanup1796083200000 implements MigrationInterface {+ async up(runner: QueryRunner): Promise<void> {+ await runner.query(`CREATE TABLE box_secret_cleanup (+ organization_id uuid NOT NULL,+ box_id varchar(64) NOT NULL,+ creating boolean NOT NULL DEFAULT false,+ available_at timestamptz NOT NULL DEFAULT now(),+ attempts integer NOT NULL DEFAULT 0,+ PRIMARY KEY (organization_id, box_id)+ )`)+ await runner.query('CREATE INDEX box_secret_cleanup_due ON box_secret_cleanup (available_at)')+ await runner.query(`CREATE FUNCTION enqueue_box_secret_cleanup() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN+ INSERT INTO box_secret_cleanup (organization_id, box_id) VALUES (OLD."organizationId", OLD.id)+ ON CONFLICT DO NOTHING;+ RETURN NULL;+ END $$`)+ await runner.query(`CREATE TRIGGER retire_destroyed_box_secrets AFTER UPDATE OF state ON box+ FOR EACH ROW WHEN (NEW.state = 'destroyed' AND OLD.state IS DISTINCT FROM NEW.state+ AND OLD.secrets @? '$[*].secretId')+ EXECUTE FUNCTION enqueue_box_secret_cleanup()`)+ await runner.query(`CREATE TRIGGER retire_deleted_box_secrets AFTER DELETE ON box+ FOR EACH ROW WHEN (OLD.secrets @? '$[*].secretId')+ EXECUTE FUNCTION enqueue_box_secret_cleanup()`)+ await runner.query(`INSERT INTO box_secret_cleanup (organization_id, box_id)+ SELECT "organizationId", id FROM box WHERE state = 'destroyed' AND secrets @? '$[*].secretId'+ ON CONFLICT DO NOTHING`)+ }++ async down(runner: QueryRunner): Promise<void> {+ await runner.query('DROP TRIGGER retire_deleted_box_secrets ON box')+ await runner.query('DROP TRIGGER retire_destroyed_box_secrets ON box')+ await runner.query('DROP FUNCTION enqueue_box_secret_cleanup()')+ await runner.query('DROP TABLE box_secret_cleanup')+ }+}diff --git a/apps/api/src/migrations/pre-deploy/1796169600000-org-secret-retirement-migration.ts b/apps/api/src/migrations/pre-deploy/1796169600000-org-secret-retirement-migration.tsnew file mode 100644index 000000000..cf4c5e6b9--- /dev/null+++ b/apps/api/src/migrations/pre-deploy/1796169600000-org-secret-retirement-migration.ts@@ -0,0 +1,48 @@+import { MigrationInterface, QueryRunner } from 'typeorm'++export class OrgSecretRetirement1796169600000 implements MigrationInterface {+ async up(runner: QueryRunner): Promise<void> {+ await runner.query(`CREATE TABLE org_secret_retirement (+ organization_id uuid NOT NULL, secret_id uuid NOT NULL,+ retry_at timestamptz DEFAULT now(),+ PRIMARY KEY (organization_id, secret_id)+ )`)+ await runner.query(+ 'CREATE INDEX org_secret_retirement_due ON org_secret_retirement (retry_at) WHERE retry_at IS NOT NULL',+ )+ // Also protects Box writes from API replicas that predate the delete endpoint.+ await runner.query(`CREATE FUNCTION guard_retired_org_secret() RETURNS trigger LANGUAGE plpgsql AS $$+ DECLARE sid text;+ BEGIN+ FOR sid IN+ SELECT DISTINCT lower(entry->>'secretId') FROM jsonb_array_elements(NEW.secrets) entry+ WHERE entry->>'secretId' IS NOT NULL ORDER BY 1+ LOOP+ IF NOT pg_try_advisory_xact_lock_shared(hashtext(NEW."organizationId"::text), hashtext(sid)) THEN+ RAISE EXCEPTION 'Secret deletion in progress' USING ERRCODE='BS001';+ END IF;+ IF current_setting('transaction_isolation') IN ('repeatable read','serializable') THEN+ -- A fixed snapshot can hide a committed deletion. The primary key still sees it.+ -- Probe keys in order and discard each new row in this same transaction.+ BEGIN+ INSERT INTO org_secret_retirement (organization_id, secret_id) VALUES (NEW."organizationId", sid::uuid);+ EXCEPTION WHEN unique_violation THEN+ RAISE EXCEPTION 'Secret has been retired' USING ERRCODE='BS001';+ END;+ DELETE FROM org_secret_retirement WHERE organization_id=NEW."organizationId" AND secret_id=sid::uuid;+ ELSIF EXISTS (SELECT FROM org_secret_retirement WHERE organization_id=NEW."organizationId" AND secret_id=sid::uuid) THEN+ RAISE EXCEPTION 'Secret has been retired' USING ERRCODE='BS001';+ END IF;+ END LOOP;+ RETURN NEW;+ END $$`)+ await runner.query(`CREATE TRIGGER guard_box_secret_bindings BEFORE INSERT OR UPDATE OF secrets ON box+ FOR EACH ROW WHEN (NEW.secrets @? '$[*].secretId') EXECUTE FUNCTION guard_retired_org_secret()`)+ }++ async down(runner: QueryRunner): Promise<void> {+ await runner.query('DROP TRIGGER guard_box_secret_bindings ON box')+ await runner.query('DROP FUNCTION guard_retired_org_secret()')+ await runner.query('DROP TABLE org_secret_retirement')+ }+}diff --git a/apps/api/src/migrations/pre-deploy/1796169600001-add-secret-read-scope-migration.ts b/apps/api/src/migrations/pre-deploy/1796169600001-add-secret-read-scope-migration.tsnew file mode 100644index 000000000..af049190f--- /dev/null+++ b/apps/api/src/migrations/pre-deploy/1796169600001-add-secret-read-scope-migration.ts@@ -0,0 +1,14 @@+import { MigrationInterface, QueryRunner } from 'typeorm'+import { addSecretScope, removeSecretScope } from '../secret-permission-scopes'++export class AddSecretReadScope1796169600001 implements MigrationInterface {+ name = 'AddSecretReadScope1796169600001'++ up(runner: QueryRunner): Promise<void> {+ return addSecretScope(runner, 'read:secrets')+ }++ down(runner: QueryRunner): Promise<void> {+ return removeSecretScope(runner, 'read:secrets')+ }+}diff --git a/apps/api/src/migrations/secret-permission-scopes.ts b/apps/api/src/migrations/secret-permission-scopes.tsnew file mode 100644index 000000000..5124fc8fe--- /dev/null+++ b/apps/api/src/migrations/secret-permission-scopes.ts@@ -0,0 +1,60 @@+import { QueryRunner } from 'typeorm'++// Freeze the old order so rollback does not depend on future application enums.+const SCOPES_BEFORE = [+ 'write:registries',+ 'delete:registries',+ 'write:templates',+ 'delete:templates',+ 'write:boxes',+ 'delete:boxes',+ 'read:volumes',+ 'write:volumes',+ 'delete:volumes',+ 'write:regions',+ 'delete:regions',+ 'read:runners',+ 'write:runners',+ 'delete:runners',+ 'read:audit_logs',+ 'read:images',+ 'delete:images',+ 'read:registries',+ 'write:images',+ 'read:members',+ 'write:members',+ 'read:apps',+ 'write:apps',+ 'delete:apps',+] as const++const SCOPE_ENUMS = [+ { type: 'api_key_permissions_enum', table: 'api_key' },+ { type: 'organization_role_permissions_enum', table: 'organization_role' },+] as const++const quoted = (scopes: readonly string[]) => scopes.map((scope) => `'${scope}'`).join(', ')++type SecretScope = 'write:secrets' | 'read:secrets'++export async function addSecretScope(queryRunner: QueryRunner, scope: SecretScope) {+ for (const { type } of SCOPE_ENUMS) {+ await queryRunner.query(`ALTER TYPE "public"."${type}" ADD VALUE IF NOT EXISTS '${scope}'`)+ }+}++export async function removeSecretScope(queryRunner: QueryRunner, scope: SecretScope) {+ const before = scope === 'write:secrets' ? SCOPES_BEFORE : [...SCOPES_BEFORE, 'write:secrets']+ for (const { type, table } of SCOPE_ENUMS) {+ await queryRunner.query(+ `UPDATE "${table}" SET permissions=array_remove(permissions, $1::"public"."${type}") WHERE $1::"public"."${type}"=ANY(permissions)`,+ [scope],+ )+ await queryRunner.query(`ALTER TYPE "public"."${type}" RENAME TO "${type}_old"`)+ await queryRunner.query(`CREATE TYPE "public"."${type}" AS ENUM(${quoted(before)})`)+ await queryRunner.query(+ `ALTER TABLE "${table}" ALTER COLUMN permissions TYPE "public"."${type}"[] USING permissions::text[]::"public"."${type}"[]`,+ )+ await queryRunner.query(`DROP TYPE "public"."${type}_old"`)+ }+}diff --git a/apps/api/src/organization/enums/organization-resource-permission.enum.ts b/apps/api/src/organization/enums/organization-resource-permission.enum.tsindex e14f23f00..fde501e9b 100644--- a/apps/api/src/organization/enums/organization-resource-permission.enum.ts+++ b/apps/api/src/organization/enums/organization-resource-permission.enum.ts@@ -57,6 +57,8 @@ export enum OrganizationResourcePermission {READ_APPS = 'read:apps',WRITE_APPS = 'write:apps',DELETE_APPS = 'delete:apps',+ WRITE_SECRETS = 'write:secrets',+ READ_SECRETS = 'read:secrets',}export const APP_HOSTING_PERMISSIONS = [diff --git a/apps/api/test/production-metadata.cjs b/apps/api/test/production-metadata.cjsindex f4720d237..125369260 100644--- a/apps/api/test/production-metadata.cjs+++ b/apps/api/test/production-metadata.cjs@@ -6,6 +6,7 @@ const { readFileSync } = require('node:fs')const { join } = require('node:path')const { test } = require('node:test')const { Socket } = require('node:net')+const { join } = require('node:path')const { NestFactory } = require('@nestjs/core')const { DataSource, getMetadataArgsStorage } = require('typeorm')@@ -37,3 +38,16 @@ test('production API bundle has valid PostgreSQL entity metadata', { timeout: 15assert.equal(dataSource.driver.normalizeType(sourceState), 'character varying')console.log(`Validated PostgreSQL metadata for ${dataSource.entityMetadatas.length} production entities`)})++test('production API discovers the secret permission and lifecycle migrations', async () => {+ const dataSource = new DataSource({+ type: 'postgres',+ migrations: [join(__dirname, '../../dist/apps/api/migrations/*-migration.js')],+ })+ await dataSource.buildMetadatas()+ const names = dataSource.migrations.map((migration) => migration.constructor.name)+ assert.ok(names.includes('AddSecretScope1795996800000'), 'missing permission migration')+ assert.ok(names.includes('OrgSecretRetirement1796169600000'), 'missing organization secret retirement migration')+ assert.ok(names.includes('AddSecretReadScope1796169600001'), 'missing read permission migration')+ assert.ok(names.includes('BoxSecretCleanup1796083200000'), 'missing cleanup migration')+})diff --git a/apps/dashboard/src/constants/CreateApiKeyPermissionsGroups.ts b/apps/dashboard/src/constants/CreateApiKeyPermissionsGroups.tsindex 96e9f2192..7f5db7e06 100644--- a/apps/dashboard/src/constants/CreateApiKeyPermissionsGroups.ts+++ b/apps/dashboard/src/constants/CreateApiKeyPermissionsGroups.ts@@ -7,6 +7,10 @@import { CreateApiKeyPermissionsEnum } from '@boxlite-ai/api-client'export const CREATE_API_KEY_PERMISSIONS_GROUPS: { name: string; permissions: CreateApiKeyPermissionsEnum[] }[] = [+ {+ name: 'Secrets',+ permissions: [CreateApiKeyPermissionsEnum.READ_SECRETS, CreateApiKeyPermissionsEnum.WRITE_SECRETS],+ },{name: 'Members',permissions: [CreateApiKeyPermissionsEnum.READ_MEMBERS, CreateApiKeyPermissionsEnum.WRITE_MEMBERS],diff --git a/apps/dashboard/src/constants/OrganizationPermissionsGroups.test.ts b/apps/dashboard/src/constants/OrganizationPermissionsGroups.test.tsindex 2ea39c6f3..db23b0ac8 100644--- a/apps/dashboard/src/constants/OrganizationPermissionsGroups.test.ts+++ b/apps/dashboard/src/constants/OrganizationPermissionsGroups.test.ts@@ -14,6 +14,10 @@ const PERMISSION_GROUPS: ReadonlyArray<readonly [string, ReadonlyArray<{ name: s]describe('permission groups', () => {+ it.each(PERMISSION_GROUPS)('offer list and management permissions for secrets in %s', (_source, groups) => {+ expect(groups.find((group) => group.name === 'Secrets')?.permissions).toEqual(['read:secrets', 'write:secrets'])+ })+it.each(PERMISSION_GROUPS)('offer App resource permissions immediately after Boxes in %s', (_source, groups) => {const boxes = groups.findIndex((group) => group.name === 'Boxes')expect(groups[boxes + 1]).toEqual({ name: 'Apps', permissions: ['read:apps', 'write:apps', 'delete:apps'] })diff --git a/apps/dashboard/src/constants/OrganizationPermissionsGroups.ts b/apps/dashboard/src/constants/OrganizationPermissionsGroups.tsindex e73034c06..d7c6cc641 100644--- a/apps/dashboard/src/constants/OrganizationPermissionsGroups.ts+++ b/apps/dashboard/src/constants/OrganizationPermissionsGroups.ts@@ -8,6 +8,10 @@ import { OrganizationRolePermissionsEnum } from '@boxlite-ai/api-client'export const ORGANIZATION_ROLE_PERMISSIONS_GROUPS: { name: string; permissions: OrganizationRolePermissionsEnum[] }[] =[+ {+ name: 'Secrets',+ permissions: [OrganizationRolePermissionsEnum.READ_SECRETS, OrganizationRolePermissionsEnum.WRITE_SECRETS],+ },{name: 'Boxes',permissions: [OrganizationRolePermissionsEnum.WRITE_BOXES, OrganizationRolePermissionsEnum.DELETE_BOXES],diff --git a/apps/dashboard/src/lib/api-key-permissions.ts b/apps/dashboard/src/lib/api-key-permissions.tsindex e0e861d52..b014fa5bb 100644--- a/apps/dashboard/src/lib/api-key-permissions.ts+++ b/apps/dashboard/src/lib/api-key-permissions.ts@@ -17,6 +17,8 @@ export const API_KEY_PERMISSION_LABELS: Record<string, string> = {'read:registries': 'View registries','write:registries': 'Manage registry credentials','delete:registries': 'Delete registry credentials',+ 'read:secrets': 'List secret names',+ 'write:secrets': 'Create and delete secrets','read:members': 'View members','write:members': 'Manage members and invitations','write:templates': 'Manage legacy templates',@@ -42,7 +44,7 @@ export const SUPPORTED_API_KEY_PERMISSIONS = Object.values(Permission).filter((permission) => permission !== Permission.UNKNOWN_DEFAULT_OPEN_API,)-const primaryGroupNames = ['Boxes', 'Apps', 'Volumes', 'Images', 'Registries', 'Members']+const primaryGroupNames = ['Boxes', 'Apps', 'Volumes', 'Images', 'Registries', 'Members', 'Secrets']const permissionGroups = [...primaryGroupNames.map((name) => CREATE_API_KEY_PERMISSIONS_GROUPS.find((group) => group.name === name)!),...CREATE_API_KEY_PERMISSIONS_GROUPS.filter((group) => !primaryGroupNames.includes(group.name)),diff --git a/apps/e2e/README.md b/apps/e2e/README.mdindex c43666266..a71e95d0e 100644--- a/apps/e2e/README.md+++ b/apps/e2e/README.md@@ -81,6 +81,24 @@ lifetimes, and reports cleanup failures. It is outside the production smokeselection because it uses checkpoint storage and multiple guest lifecycles. Loopback, mock-storage andnative stub checks do not satisfy this real VM/storage acceptance case.+### Named secret lifecycle++Run the named secret case against a disposable deployment with Secret Server write and fetch roles, a registered Runner, and HTTPS preview access.++- Give the owner API key Box creation, `read:secrets`, and `write:secrets` permissions.+- Set `BOXLITE_E2E_FOREIGN_PROFILE` to a Box creator in a second organization on the same API.+- Set `BOXLITE_E2E_SECRET_PGSERVICE` to a libpq service that can count Box-owned rows in the Secret Server's `secret` table.++With the checkout's Python SDK installed and the API profile configured, run+`pytest apps/e2e/cases/test_named_secret_lifecycle.py -v` from the repository root.++| Box lifecycle | Expected result |+| --- | --- |+| A runs, then stops before B exists | Both HTTPS requests succeed while A runs. Stopped A alone blocks deletion of the shared ID with 409. |+| B starts, then A restarts | B uses the shared secret. A repeats the private and shared HTTPS requests successfully. |+| A is destroyed | A's private row disappears. B makes a fresh HTTPS request and alone blocks deletion with 409. |+| B is destroyed | Deleting the shared ID and repeating the delete both return 204. The ID disappears from the list. |+### Dashboard QuickstartEvery dev run renders and executes the Dashboard's **Copy full example**diff --git a/apps/e2e/cases/test_named_secret_lifecycle.py b/apps/e2e/cases/test_named_secret_lifecycle.pynew file mode 100644index 000000000..0eafc334c--- /dev/null+++ b/apps/e2e/cases/test_named_secret_lifecycle.py@@ -0,0 +1,236 @@+"""Mixed Box secrets through a real Runner, a verdict-only HTTPS upstream and PostgreSQL."""++import asyncio+import hashlib+import os+import secrets+import subprocess+from contextlib import AsyncExitStack+from pathlib import Path+from urllib.parse import urlencode, urlsplit++import pytest+from conftest import drain+from e2e_auth import discover_path_prefix, load_profile, request_json+from network_fixtures import prepare, service_box, state+from preview import access, require++import boxlite+++async def verify(box, uri, policies, original_values):+ execution = await box.exec("env", [], None)+ stdout, stderr = await drain(execution)+ require((await execution.wait()).exit_code == 0, "guest environment unavailable")+ require(+ all(value not in stdout + stderr for value in original_values),+ "guest environment contains an original value",+ )+ for path, name in policies:+ placeholder = f"<BOXLITE_SECRET:{name}>"+ require(+ f"BOXLITE_SECRET_{name.upper()}={placeholder}" in stdout.splitlines(),+ "secret placeholder missing in guest",+ )+ probe = await box.exec(+ "curl",+ [+ "--silent",+ "--show-error",+ "--max-time",+ "20",+ "--output",+ "/dev/null",+ "--write-out",+ "%{http_code}",+ "--header",+ "X-BoxLite-Skip-Preview-Warning: true",+ "--header",+ f"X-Test-{path}: dummy",+ f"{uri.rstrip('/')}/{path}",+ ],+ None,+ )+ output, _ = await drain(probe)+ require(+ (await probe.wait()).exit_code == 0 and output == "204",+ f"upstream rejected the {path} policy",+ )+++def private_count(box_id, service):+ proc = subprocess.run(+ ["psql", "-XqAt", "-v", "ON_ERROR_STOP=1", "-v", f"box={box_id}"],+ input="SELECT count(*) FROM secret WHERE scope='box' AND box_id=:'box';",+ env={**os.environ, "PGSERVICE": service},+ check=False,+ capture_output=True,+ text=True,+ timeout=10,+ )+ require(proc.returncode == 0, "Secret Server database check failed")+ return int(proc.stdout.strip())+++def listed_secret(secret_id):+ query = {"pageSize": 100}+ while True:+ status, page = request_json("GET", "/v1/secrets?" + urlencode(query))+ require(status == 200, "organization secret listing failed")+ for item in page["secrets"]:+ require(+ set(item) == {"id", "name", "hosts", "headers", "placeholder"},+ "unexpected organization secret list fields",+ )+ if item["id"] == secret_id:+ return item+ if "next_page_token" not in page:+ return None+ query["pageToken"] = page["next_page_token"]+++async def delete_after_destruction(path):+ async with asyncio.timeout(180):+ while True:+ status, _ = request_json("DELETE", path)+ if status == 204:+ return+ require(status == 409, "organization secret deletion failed")+ await asyncio.sleep(1)+++async def test_named_secret_lifecycle(rt, image, e2e_auth):+ service = os.getenv("BOXLITE_E2E_SECRET_PGSERVICE")+ if not service:+ pytest.skip(+ "requires a libpq service for the disposable Secret Server database"+ )+ foreign = load_profile(os.environ["BOXLITE_E2E_FOREIGN_PROFILE"])+ require(+ foreign["url"].rstrip("/") == e2e_auth.url.rstrip("/"),+ "profiles must use the same API",+ )+ foreign_prefix = discover_path_prefix(e2e_auth.url, foreign["api_key"])+ require(+ foreign_prefix+ and e2e_auth.path_prefix+ and foreign_prefix != e2e_auth.path_prefix,+ "profiles must belong to different organizations",+ )+ shared_name = "shared_" + secrets.token_hex(6)+ shared, private = secrets.token_hex(32), secrets.token_hex(32)+ upstream = (Path(__file__).parents[1] / "fixtures/secret_verdict.py").read_text()+ digests = [hashlib.sha256(v.encode()).hexdigest() for v in (shared, private)]+ async with service_box(+ rt, image, entrypoint=["python3", "-u", "-c", upstream, *digests]+ ) as (server, _):+ tunnel = await prepare(server)+ uri = tunnel.uri()+ host = urlsplit(uri).hostname+ require(+ urlsplit(uri).scheme == "https" and host, "verdict upstream requires HTTPS"+ )+ async with asyncio.timeout(45):+ while True:+ control = await access(+ uri.rstrip("/") + "/shared",+ headers={"X-BoxLite-Skip-Preview-Warning": "true"},+ )+ if control.status not in (502, 503):+ break+ await asyncio.sleep(0.2)+ require(+ control.status == 403 and not control.body,+ "verdict upstream must reject a request with no credential",+ )+ status, identity = request_json(+ "POST",+ "/v1/secrets",+ {+ "name": shared_name,+ "value": shared,+ "hosts": [host],+ "headers": {"X-Test-Shared": "{value}"},+ },+ )+ require(+ status == 201+ and set(identity) == {"id", "name"}+ and identity["name"] == shared_name,+ "organization secret creation failed",+ )+ ref = {"secret": shared_name}+ inline = boxlite.Secret(+ "private", private, [host], headers={"X-Test-Private": "{value}"}+ )+ other = boxlite.Boxlite.rest(+ boxlite.BoxliteRestOptions(+ url=foreign["url"],+ credential=boxlite.ApiKeyCredential(foreign["api_key"]),+ path_prefix=foreign_prefix,+ )+ )+ path = "/v1/secrets/" + identity["id"]+ async with AsyncExitStack() as boxes:+ boxes.push_async_callback(delete_after_destruction, path)+ require(+ listed_secret(identity["id"])+ == {+ **identity,+ "hosts": [host],+ "headers": {"X-Test-Shared": "{value}"},+ "placeholder": f"<BOXLITE_SECRET:{shared_name}>",+ },+ "listed organization secret policy differs from the saved policy",+ )+ try:+ try:+ unexpected = await other.create(+ boxlite.BoxOptions(image=image, secrets=[ref])+ )+ except boxlite.NotFoundError as err:+ require(+ "secret not found" in str(err).lower(),+ "expected a missing organization secret",+ )+ else:+ await other.remove(unexpected.id, force=True)+ pytest.fail("another organization resolved the private name")+ finally:+ other.close()+ a = await rt.create(+ boxlite.BoxOptions(+ image=image, auto_remove=False, secrets=[inline, ref]+ )+ )+ async with AsyncExitStack() as owner:+ owner.push_async_callback(rt.remove, a.id, force=True)+ original_values = (shared, private)+ shared_policy = ("shared", shared_name)+ mixed = [("private", "private"), shared_policy]+ await verify(a, uri, mixed, original_values)+ assert private_count(a.id, service) == 1+ await a.stop()+ await state(rt, a.id, "stopped")+ assert private_count(a.id, service) == 1+ require(+ request_json("DELETE", path)[0] == 409,+ "stopped Box lost its reference",+ )+ b = await rt.create(boxlite.BoxOptions(image=image, secrets=[ref]))+ boxes.push_async_callback(rt.remove, b.id, force=True)+ await verify(b, uri, [shared_policy], original_values)+ await a.start()+ await state(rt, a.id, "running")+ await verify(a, uri, mixed, original_values)+ async with asyncio.timeout(180):+ while private_count(a.id, service):+ await asyncio.sleep(1)+ await verify(b, uri, [shared_policy], original_values)+ require(+ request_json("DELETE", path)[0] == 409,+ "Box B lost its shared reference",+ )+ require(request_json("DELETE", path)[0] == 204, "owner deletion retry failed")+ assert listed_secret(identity["id"]) is Nonediff --git a/apps/e2e/fixtures/secret_verdict.py b/apps/e2e/fixtures/secret_verdict.pynew file mode 100644index 000000000..4ffc01c39--- /dev/null+++ b/apps/e2e/fixtures/secret_verdict.py@@ -0,0 +1,28 @@+"""Test upstream for Box-owned and organization secret injection."""++import hashlib+import sys+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+++class Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ expected = {+ "/shared": ("X-Test-Shared", sys.argv[1]),+ "/private": ("X-Test-Private", sys.argv[2]),+ }+ rule = expected.get(self.path)+ status = 404+ if rule:+ header, digest = rule+ actual = hashlib.sha256(self.headers.get(header, "").encode()).hexdigest()+ status = 204 if actual == digest else 403+ self.send_response(status)+ self.send_header("Content-Length", "0")+ self.end_headers()++ def log_message(self, *args):+ pass+++ThreadingHTTPServer(("0.0.0.0", 18080), Handler).serve_forever()diff --git a/apps/infra/deployment/workflow-checks.test.ts b/apps/infra/deployment/workflow-checks.test.tsindex 5b4079836..051fcef47 100644--- a/apps/infra/deployment/workflow-checks.test.ts+++ b/apps/infra/deployment/workflow-checks.test.ts@@ -193,9 +193,10 @@ for (const [path, expected] of [['sdks/go/options.go', ['rust', 'go']],['sdks/go/integration/archive/checkpoint_test.go', ['rust', 'go']],['apps/runner/cmd/runner/main.go', ['go']],- ['apps/secret-server/internal/encryption/cipher.go', ['go']],+ ['apps/secret-server/internal/encryption/cipher.go', ['go', 'api']],['apps/secret-server/internal/encryption/cipher_test.go', ['go']],- ['apps/secret-server/go.mod', ['go']],+ ['apps/secret-server/go.mod', ['go', 'api']],+ ['apps/secret-server/tests/secret-list-api.sh', ['go', 'api']],['sdks/python/boxlite/options.py', ['rust', 'python']],['sdks/python/boxlite/sync_api/_ssh.py', ['rust', 'python']],['sdks/python/tests/test_ssh_native_rest.py', ['rust', 'python']],diff --git a/apps/libs/api-client-go/api/openapi.yaml b/apps/libs/api-client-go/api/openapi.yamlindex 093b1f8f7..0fe6467d2 100644--- a/apps/libs/api-client-go/api/openapi.yaml+++ b/apps/libs/api-client-go/api/openapi.yaml@@ -6404,6 +6404,8 @@ components:- read:apps- write:apps- delete:apps+ - write:secrets+ - read:secretstype: stringtype: arrayisGlobal:@@ -6817,6 +6819,8 @@ components:- read:apps- write:apps- delete:apps+ - write:secrets+ - read:secretstype: stringtype: arrayrequired:@@ -6868,6 +6872,8 @@ components:- read:apps- write:apps- delete:apps+ - write:secrets+ - read:secretstype: stringtype: arrayrequired:@@ -7887,6 +7893,8 @@ components:- read:apps- write:apps- delete:apps+ - write:secrets+ - read:secretstype: stringtype: arrayexpiresAt:@@ -7950,6 +7958,8 @@ components:- read:apps- write:apps- delete:apps+ - write:secrets+ - read:secretstype: stringtype: arrayexpiresAt:@@ -8019,6 +8029,8 @@ components:- read:apps- write:apps- delete:apps+ - write:secrets+ - read:secretstype: stringtype: arraylastUsedAt:diff --git a/apps/libs/api-client/src/models/api-key-list.ts b/apps/libs/api-client/src/models/api-key-list.tsindex 30007b809..d72eaf78c 100644--- a/apps/libs/api-client/src/models/api-key-list.ts+++ b/apps/libs/api-client/src/models/api-key-list.ts@@ -70,6 +70,8 @@ export const ApiKeyListPermissionsEnum = {READ_APPS: 'read:apps',WRITE_APPS: 'write:apps',DELETE_APPS: 'delete:apps',+ WRITE_SECRETS: 'write:secrets',+ READ_SECRETS: 'read:secrets',UNKNOWN_DEFAULT_OPEN_API: '11184809',} as const;diff --git a/apps/libs/api-client/src/models/api-key-response.ts b/apps/libs/api-client/src/models/api-key-response.tsindex 32a13bd0f..e13a75561 100644--- a/apps/libs/api-client/src/models/api-key-response.ts+++ b/apps/libs/api-client/src/models/api-key-response.ts@@ -62,6 +62,8 @@ export const ApiKeyResponsePermissionsEnum = {READ_APPS: 'read:apps',WRITE_APPS: 'write:apps',DELETE_APPS: 'delete:apps',+ WRITE_SECRETS: 'write:secrets',+ READ_SECRETS: 'read:secrets',UNKNOWN_DEFAULT_OPEN_API: '11184809',} as const;diff --git a/apps/libs/api-client/src/models/create-api-key.ts b/apps/libs/api-client/src/models/create-api-key.tsindex 468ff72eb..17a76b97b 100644--- a/apps/libs/api-client/src/models/create-api-key.ts+++ b/apps/libs/api-client/src/models/create-api-key.ts@@ -54,6 +54,8 @@ export const CreateApiKeyPermissionsEnum = {READ_APPS: 'read:apps',WRITE_APPS: 'write:apps',DELETE_APPS: 'delete:apps',+ WRITE_SECRETS: 'write:secrets',+ READ_SECRETS: 'read:secrets',UNKNOWN_DEFAULT_OPEN_API: '11184809',} as const;diff --git a/apps/libs/api-client/src/models/create-organization-role.ts b/apps/libs/api-client/src/models/create-organization-role.tsindex 0ea0f189a..8d6aa9c59 100644--- a/apps/libs/api-client/src/models/create-organization-role.ts+++ b/apps/libs/api-client/src/models/create-organization-role.ts@@ -54,6 +54,8 @@ export const CreateOrganizationRolePermissionsEnum = {READ_APPS: 'read:apps',WRITE_APPS: 'write:apps',DELETE_APPS: 'delete:apps',+ WRITE_SECRETS: 'write:secrets',+ READ_SECRETS: 'read:secrets',UNKNOWN_DEFAULT_OPEN_API: '11184809',} as const;diff --git a/apps/libs/api-client/src/models/organization-role.ts b/apps/libs/api-client/src/models/organization-role.tsindex 515a9f9ff..71ece7f5f 100644--- a/apps/libs/api-client/src/models/organization-role.ts+++ b/apps/libs/api-client/src/models/organization-role.ts@@ -70,6 +70,8 @@ export const OrganizationRolePermissionsEnum = {READ_APPS: 'read:apps',WRITE_APPS: 'write:apps',DELETE_APPS: 'delete:apps',+ WRITE_SECRETS: 'write:secrets',+ READ_SECRETS: 'read:secrets',UNKNOWN_DEFAULT_OPEN_API: '11184809',} as const;diff --git a/apps/libs/api-client/src/models/update-organization-role.ts b/apps/libs/api-client/src/models/update-organization-role.tsindex a4c8288d6..6843ce463 100644--- a/apps/libs/api-client/src/models/update-organization-role.ts+++ b/apps/libs/api-client/src/models/update-organization-role.ts@@ -54,6 +54,8 @@ export const UpdateOrganizationRolePermissionsEnum = {READ_APPS: 'read:apps',WRITE_APPS: 'write:apps',DELETE_APPS: 'delete:apps',+ WRITE_SECRETS: 'write:secrets',+ READ_SECRETS: 'read:secrets',UNKNOWN_DEFAULT_OPEN_API: '11184809',} as const;diff --git a/apps/secret-server/README.md b/apps/secret-server/README.mdindex 22320acb5..110280b4e 100644--- a/apps/secret-server/README.md+++ b/apps/secret-server/README.md@@ -36,6 +36,18 @@ transfers and `GET /internal/v1/secrets/{secret_id}` for metadata. A successfultransfer returns secret IDs without values. Identical retries return the same IDs;a changed value or policy returns `secret_conflict`.+The write role serves the following operations under `/internal/v1/organizations/{org_id}/secrets`.++| Method and path relative to the collection | Result |+| --- | --- |+| POST collection | Create a named credential. |+| GET collection | Return `id`, `name`, `hosts`, `headers` (stored templates), and `placeholder`, ordered by ID. Use `limit` (1–1001) and an optional UUID cursor `after`. |+| POST `/resolve` | Resolve names to IDs and routing policy. |+| HEAD `/{secret_id}` | Confirm organization ownership with 204 or return 404. |+| DELETE `/{secret_id}` | Remove the organization's record. Repeat delivery returns 204. |++The hosted API verifies Box references before sending a delete.+The secret store serializes transfers for each box with a transaction-scoped lock.It checks the organization before names, and rolls back the batch if retry comparisonfails. Metadata reads do not retrieve encrypted values.diff --git a/apps/secret-server/cmd/secret-server/credential_api_test.go b/apps/secret-server/cmd/secret-server/credential_api_test.goindex 24254e7eb..484a94ed1 100644--- a/apps/secret-server/cmd/secret-server/credential_api_test.go+++ b/apps/secret-server/cmd/secret-server/credential_api_test.go@@ -129,4 +129,104 @@ func TestCredentialAPIIntegration(t *testing.T) {}})}+ t.Run("mixed and shared Box bindings survive fresh grants and retirement", func(t *testing.T) {+ testMixedBoxGrants(t, ctx, strings.TrimSuffix(fetchURL, "/internal/v1/secrets/fetch"), endpoint, pool)+ })++}++// Verify that the IDs returned by the write role go through the production+// credential API and fetch role before and after private records are retired.+func testMixedBoxGrants(t *testing.T, ctx context.Context, server, issuer string, pool *pgxpool.Pool) {+ const org = "11111111-1111-1111-1111-111111111111"+ const foreign = "99999999-9999-4999-8999-999999999999"+ const a, b = "BoxMixed0001", "BoxMixed0002"+ call := func(method, url string, payload any, headers map[string]string, status int, result any) {+ t.Helper()+ var body io.Reader+ if payload != nil {+ wire, err := json.Marshal(payload)+ if err != nil {+ t.Fatal(err)+ }+ body = bytes.NewReader(wire)+ }+ req, err := http.NewRequestWithContext(ctx, method, url, body)+ if err != nil {+ t.Fatal(err)+ }+ for k, v := range headers {+ req.Header.Set(k, v)+ }+ req.Header.Set("Content-Type", "application/json")+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer resp.Body.Close()+ if resp.StatusCode != status {+ t.Fatalf("%s %s: got %d, want %d", method, req.URL.Path, resp.StatusCode, status)+ }+ if result != nil {+ if err := json.NewDecoder(resp.Body).Decode(result); err != nil {+ t.Fatal(err)+ }+ }+ }+ write := map[string]string{"Authorization": "Bearer " + os.Getenv("SECRET_SERVER_DEV_TOKEN")}+ secret := func(name string) map[string]any {+ return map[string]any{"name": name, "value": "value-" + name, "hosts": []string{name + ".example.com"},+ "headers": map[string]string{"X-Key": "{value}"}, "placeholder": "placeholder-" + name}+ }+ orgPath := func(id string) string { return server + "/internal/v1/organizations/" + id + "/secrets" }+ boxPath := server + "/internal/v1/boxes/" + a + "/secrets"+ var created struct{ ID string }+ call("POST", orgPath(org), map[string]any{"created_by": "owner", "secret": secret("shared")}, write, 201, &created)+ query := map[string]any{"names": []string{"shared"}}+ call("POST", orgPath(foreign)+"/resolve", query, write, 404, nil)+ var resolved struct{ Secrets []struct{ ID string } }+ call("POST", orgPath(org)+"/resolve", query, write, 200, &resolved)+ if len(resolved.Secrets) != 1 || resolved.Secrets[0].ID != created.ID || created.ID == "" {+ t.Fatal("shared resolution changed identity")+ }+ var stored struct {+ Secrets []struct {+ ID string `json:"secret_id"`+ }+ }+ call("POST", boxPath, map[string]any{"org_id": org, "created_by": "owner", "secrets": []any{secret("private")}}, write, 201, &stored)+ if len(stored.Secrets) != 1 || stored.Secrets[0].ID == "" {+ t.Fatal("missing private mapping")+ }+ fetchValues := func(box string, ids, names []string) {+ t.Helper()+ var issued struct{ Token string }+ call("POST", issuer+"/__test/issue", map[string]any{"runnerId": "runner-a", "boxId": box, "organizationId": org, "secretIds": ids}, nil, 200, &issued)+ var fetched struct {+ BoxID string `json:"box_id"`+ Secrets []struct{ Name, Value string }+ }+ call("POST", server+"/internal/v1/secrets/fetch", map[string]string{"credential": issued.Token}, map[string]string{attest.DevHeader: "runner-a"}, 200, &fetched)+ if fetched.BoxID != box || len(fetched.Secrets) != len(names) {+ t.Fatal("incorrect fetch binding")+ }+ for i, name := range names {+ if fetched.Secrets[i].Name != name || fetched.Secrets[i].Value != "value-"+name {+ t.Fatal("incorrect fetched secret")+ }+ }+ }+ mixed := []string{stored.Secrets[0].ID, resolved.Secrets[0].ID}+ shared := mixed[1:]+ fetchValues(a, mixed, []string{"private", "shared"})+ fetchValues(b, shared, []string{"shared"})+ fetchValues(a, mixed, []string{"private", "shared"})+ write["X-Boxlite-Organization-Id"] = org+ call("DELETE", boxPath, nil, write, 204, nil)+ call("DELETE", boxPath, nil, write, 204, nil)+ var count int+ if err := pool.QueryRow(ctx, "SELECT count(*) FROM secret WHERE box_id=$1 AND scope='box'", a).Scan(&count); err != nil || count != 0 {+ t.Fatal("private record remained after retirement", err)+ }+ fetchValues(b, shared, []string{"shared"})}diff --git a/apps/secret-server/internal/database/database.go b/apps/secret-server/internal/database/database.goindex 4db912f81..b082a2df3 100644--- a/apps/secret-server/internal/database/database.go+++ b/apps/secret-server/internal/database/database.go@@ -20,7 +20,7 @@ import (//go:embed migrations/*.sqlvar migrationFiles embed.FS-const schemaVersion = 2+const schemaVersion = 3type boundedSessionLocker struct{ lock.SessionLocker }diff --git a/apps/secret-server/internal/database/database_test.go b/apps/secret-server/internal/database/database_test.goindex 59d057d0a..3392e9a09 100644--- a/apps/secret-server/internal/database/database_test.go+++ b/apps/secret-server/internal/database/database_test.go@@ -327,7 +327,7 @@ func TestIntegration(t *testing.T) {if err := Migrate(ctx, pool); err != nil {t.Fatal(err)}- if _, err := pool.Exec(ctx, `INSERT INTO goose_db_version (version_id, is_applied) VALUES (3, true)`); err != nil {+ if _, err := pool.Exec(ctx, `INSERT INTO goose_db_version (version_id, is_applied) VALUES ($1, true)`, schemaVersion+1); err != nil {t.Fatal(err)}if err := Migrate(ctx, pool); err != nil {diff --git a/apps/secret-server/internal/database/migrations/00003_retired_box_secret_owner.sql b/apps/secret-server/internal/database/migrations/00003_retired_box_secret_owner.sqlnew file mode 100644index 000000000..41da66030--- /dev/null+++ b/apps/secret-server/internal/database/migrations/00003_retired_box_secret_owner.sql@@ -0,0 +1,6 @@+-- +goose Up+CREATE TABLE retired_box_secret_owner (+ organization_id uuid NOT NULL,+ box_id varchar(64) NOT NULL,+ PRIMARY KEY (organization_id, box_id)+);diff --git a/apps/secret-server/internal/secretstore/organization.go b/apps/secret-server/internal/secretstore/organization.gonew file mode 100644index 000000000..ab18cf9b4--- /dev/null+++ b/apps/secret-server/internal/secretstore/organization.go@@ -0,0 +1,68 @@+package secretstore++import (+ "context"+ "errors"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgxpool"+)++var ErrOrganizationNameConflict = errors.New("organization secret name already exists")++func ListOrganizationSecrets(ctx context.Context, db *pgxpool.Pool, org, after string, limit int) ([]Reference, error) {+ rows, err := db.Query(ctx, `SELECT id::text, name, hosts, headers, placeholder FROM secret+ WHERE organization_id=$1 AND scope='org' AND (NULLIF($2::text,'') IS NULL OR id>NULLIF($2::text,'')::uuid)+ ORDER BY id LIMIT $3`, org, after, limit)+ if err != nil {+ return nil, err+ }+ return pgx.CollectRows(rows, pgx.RowToStructByPos[Reference])+}++func CheckOrganizationSecret(ctx context.Context, db *pgxpool.Pool, org, id string) error {+ var exists bool+ return db.QueryRow(ctx, "SELECT true FROM secret WHERE organization_id=$1 AND id=$2 AND scope='org'", org, id).Scan(&exists)+}++func DeleteOrganizationSecret(ctx context.Context, db *pgxpool.Pool, org, id string) error {+ _, err := db.Exec(ctx, "DELETE FROM secret WHERE organization_id=$1 AND id=$2 AND scope='org'", org, id)+ return err+}++func InsertOrganizationSecret(ctx context.Context, db *pgxpool.Pool, org string, s Secret) error {+ m := s.Metadata+ tag, err := db.Exec(ctx, `INSERT INTO secret+ (id,organization_id,scope,name,name_normalized,ciphertext,encrypted_dek,key_id,hosts,headers,placeholder,created_by)+ VALUES ($1,$2,'org',$3,$4,$5,$6,$7,$8,$9,$10,$11)+ ON CONFLICT (organization_id,name_normalized) WHERE scope='org' DO NOTHING`,+ m.ID, org, m.Name, m.NormalizedName, s.Envelope.Ciphertext, s.Envelope.WrappedDEK.Ciphertext, s.Envelope.WrappedDEK.KeyID, m.Hosts, m.Headers, m.Placeholder, m.CreatedBy)+ if err == nil && tag.RowsAffected() == 0 {+ return ErrOrganizationNameConflict+ }+ return err+}++type Reference struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Hosts []string `json:"hosts"`+ Headers map[string]string `json:"headers"`+ Placeholder string `json:"placeholder"`+}++func ResolveOrganizationSecrets(ctx context.Context, db *pgxpool.Pool, org string, names []string) ([]Reference, error) {+ rows, err := db.Query(ctx, `SELECT s.id::text,s.name,s.hosts,s.headers,s.placeholder+ FROM unnest($2::text[]) WITH ORDINALITY AS requested(name,position)+ JOIN secret s ON s.organization_id=$1 AND s.scope='org' AND s.disabled_at IS NULL+ AND s.name_normalized=requested.name+ ORDER BY requested.position`, org, names)+ if err != nil {+ return nil, err+ }+ refs, err := pgx.CollectRows(rows, pgx.RowToStructByPos[Reference])+ if err == nil && len(refs) != len(names) {+ return nil, pgx.ErrNoRows+ }+ return refs, err+}diff --git a/apps/secret-server/internal/secretstore/store.go b/apps/secret-server/internal/secretstore/store.goindex d5989626d..7b231c36c 100644--- a/apps/secret-server/internal/secretstore/store.go+++ b/apps/secret-server/internal/secretstore/store.go@@ -14,6 +14,7 @@ import ()var (+ ErrBoxRetired = errors.New("box secret owner has retired")ErrBoxOrgMismatch = errors.New("box belongs to another organization")ErrBoxSecretsExist = errors.New("box already has secrets"))@@ -61,6 +62,13 @@ func InsertBoxSecrets(ctx context.Context, pool *pgxpool.Pool, orgID, boxID striif _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock($1, hashtext($2))", boxLockClass, boxID); err != nil {return nil, fmt.Errorf("lock box: %w", err)}+ var retired bool+ if err := tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM retired_box_secret_owner WHERE organization_id=$1 AND box_id=$2)", orgID, boxID).Scan(&retired); err != nil {+ return nil, fmt.Errorf("read box secrets: check retirement: %w", err)+ }+ if retired {+ return nil, ErrBoxRetired+ }rows, err := tx.Query(ctx, "SELECT organization_id <> $2::uuid, name_normalized FROM secret WHERE scope='box' AND box_id=$1", boxID, orgID)if err != nil {return nil, fmt.Errorf("read box secrets: %w", err)@@ -150,3 +158,19 @@ func ReadMetadata(ctx context.Context, pool *pgxpool.Pool, id string) (Metadata,}return m, nil}++// RetireBoxSecrets uses READ COMMITTED so the delete sees a transfer that+// committed while cleanup waited for the Box lock.+// The marker fences a write that reaches this database after cleanup succeeds.+func RetireBoxSecrets(ctx context.Context, pool *pgxpool.Pool, orgID, boxID string) error {+ return pgx.BeginTxFunc(ctx, pool, pgx.TxOptions{IsoLevel: pgx.ReadCommitted}, func(tx pgx.Tx) error {+ if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock($1, hashtext($2))", boxLockClass, boxID); err != nil {+ return err+ }+ if _, err := tx.Exec(ctx, "INSERT INTO retired_box_secret_owner(organization_id,box_id) VALUES ($1,$2) ON CONFLICT DO NOTHING", orgID, boxID); err != nil {+ return err+ }+ _, err := tx.Exec(ctx, "DELETE FROM secret WHERE organization_id=$1 AND box_id=$2 AND scope='box'", orgID, boxID)+ return err+ })+}diff --git a/apps/secret-server/internal/secretstore/store_test.go b/apps/secret-server/internal/secretstore/store_test.goindex ed1b653b7..2e754d074 100644--- a/apps/secret-server/internal/secretstore/store_test.go+++ b/apps/secret-server/internal/secretstore/store_test.go@@ -166,6 +166,134 @@ func TestIntegration(t *testing.T) {t.Fatalf("timed-out transfer left %d rows: %v", count, err)}+ t.Run("retirement sees a transfer committed during its lock wait", func(t *testing.T) {+ const owner = "Box333333333"+ config := pool.Config()+ config.ConnConfig.RuntimeParams["default_transaction_isolation"] = "repeatable read"+ config.ConnConfig.RuntimeParams["application_name"] = "retire-box-lock-test"+ cleanupPool, err := pgxpool.NewWithConfig(ctx, config)+ if err != nil {+ t.Fatal(err)+ }+ defer cleanupPool.Close()+ ctx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()+ observer, err := pool.Acquire(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer observer.Release()+ writer, err := pool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer writer.Rollback(context.Background())+ if _, err := writer.Exec(ctx, "SELECT pg_advisory_xact_lock($1, hashtext($2))", boxLockClass, owner); err != nil {+ t.Fatal(err)+ }+ s := secret("10000000-0000-4000-8000-000000000013", "PRIVATE", "value")+ _, err = writer.Exec(ctx, `INSERT INTO secret+ (id, organization_id, scope, box_id, name, name_normalized, ciphertext, encrypted_dek, key_id, hosts, headers, placeholder, created_by)+ VALUES ($1, $2, 'box', $3, $4, $4, $5, $6, $7, $8, $9, $10, $11)`,+ s.Metadata.ID, org, owner, s.Metadata.Name, s.Envelope.Ciphertext, s.Envelope.WrappedDEK.Ciphertext,+ s.Envelope.WrappedDEK.KeyID, s.Metadata.Hosts, s.Metadata.Headers, s.Metadata.Placeholder, s.Metadata.CreatedBy)+ if err != nil {+ t.Fatal(err)+ }+ done := make(chan error, 1)+ go func() { done <- RetireBoxSecrets(ctx, cleanupPool, org, owner) }()+ for {+ var blocked bool+ err := observer.QueryRow(ctx, `SELECT EXISTS (+ SELECT FROM pg_stat_activity WHERE datname=current_database() AND application_name='retire-box-lock-test'+ AND wait_event='advisory' AND $1 = ANY(pg_blocking_pids(pid)))`, int32(writer.Conn().PgConn().PID())).Scan(&blocked)+ if err != nil {+ t.Fatal(err)+ }+ if blocked {+ break+ }+ select {+ case err := <-done:+ t.Fatalf("retirement finished before waiting for the writer: %v", err)+ case <-ctx.Done():+ t.Fatal("retirement did not reach the writer's lock")+ case <-time.After(10 * time.Millisecond):+ }+ }+ if err := writer.Commit(ctx); err != nil {+ t.Fatal(err)+ }+ if err := <-done; err != nil {+ t.Fatal(err)+ }+ var remaining int+ var retired bool+ err = observer.QueryRow(ctx, `SELECT+ (SELECT count(*) FROM secret WHERE organization_id=$1 AND box_id=$2 AND scope='box'),+ EXISTS (SELECT FROM retired_box_secret_owner WHERE organization_id=$1 AND box_id=$2)`, org, owner).Scan(&remaining, &retired)+ if err != nil {+ t.Fatal(err)+ }+ if remaining != 0 || !retired {+ t.Fatalf("committed retirement: private rows=%d, retired=%t; want 0, true", remaining, retired)+ }+ })++ t.Run("retirement rolls back on lock timeout and can be retried", func(t *testing.T) {+ const owner = "Box444444444"+ value := secret("10000000-0000-4000-8000-000000000014", "PRIVATE", "value")+ if _, err := InsertBoxSecrets(ctx, pool, org, owner, []Secret{value}, reject); err != nil {+ t.Fatal(err)+ }+ config := pool.Config()+ config.ConnConfig.RuntimeParams["lock_timeout"] = "150ms"+ cleanup, err := pgxpool.NewWithConfig(ctx, config)+ if err != nil {+ t.Fatal(err)+ }+ defer cleanup.Close()+ checkState := func(t *testing.T, wantSecret, wantRetired bool) {+ t.Helper()+ var present, retired bool+ err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT FROM secret WHERE id=$1),+ EXISTS (SELECT FROM retired_box_secret_owner WHERE organization_id=$2 AND box_id=$3)`,+ value.Metadata.ID, org, owner).Scan(&present, &retired)+ if err != nil || present != wantSecret || retired != wantRetired {+ t.Fatalf("secret present=%t, retired=%t, error=%v; want %t, %t", present, retired, err, wantSecret, wantRetired)+ }+ }+ for _, tc := range []struct {+ name, lock string+ args []any+ }{+ {"Box lock", "SELECT pg_advisory_xact_lock($1, hashtext($2))", []any{boxLockClass, owner}},+ {"retirement marker", "LOCK TABLE retired_box_secret_owner IN SHARE MODE", nil},+ {"ciphertext delete", "LOCK TABLE secret IN SHARE MODE", nil},+ } {+ t.Run(tc.name, func(t *testing.T) {+ blocker, err := pool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer blocker.Rollback(ctx)+ if _, err := blocker.Exec(ctx, tc.lock, tc.args...); err != nil {+ t.Fatal(err)+ }+ err = RetireBoxSecrets(ctx, cleanup, org, owner)+ var pgErr *pgconn.PgError+ if !errors.As(err, &pgErr) || pgErr.Code != "55P03" {+ t.Fatalf("retirement error = %v, want lock timeout", err)+ }+ checkState(t, true, false)+ })+ }+ if err := RetireBoxSecrets(ctx, pool, org, owner); err != nil {+ t.Fatal(err)+ }+ checkState(t, false, true)+ })+t.Run("canceled transfer cannot begin", func(t *testing.T) {canceled, cancel := context.WithCancel(ctx)cancel()diff --git a/apps/secret-server/internal/server/organization_handlers.go b/apps/secret-server/internal/server/organization_handlers.gonew file mode 100644index 000000000..c9f5dc909--- /dev/null+++ b/apps/secret-server/internal/server/organization_handlers.go@@ -0,0 +1,168 @@+package server++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "strconv"+ "time"++ "github.com/boxlite-ai/secret-server/internal/database"+ "github.com/boxlite-ai/secret-server/internal/secretstore"+ "github.com/jackc/pgx/v5"+)++func (a *writeAPI) listOrganizationSecrets(w http.ResponseWriter, r *http.Request) {+ org := r.PathValue("org_id")+ if !isUUID(org) {+ writeProblem(w, invalid("org_id_invalid", "org_id"))+ return+ }+ q := r.URL.Query()+ after := q.Get("after")+ limit, err := strconv.Atoi(q.Get("limit"))+ if err != nil || limit < 1 || limit > 1001 || (after != "" && !isUUID(after)) {+ writeProblem(w, invalid("invalid_page", "query"))+ return+ }+ ctx, cancel := context.WithTimeout(r.Context(), metadataTimeout)+ defer cancel()+ items, err := secretstore.ListOrganizationSecrets(ctx, a.pool, org, after, limit)+ if err != nil {+ writeProblem(w, transferError(ctx, err))+ return+ }+ w.Header().Set("Cache-Control", "no-store")+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"secrets": items})+}++func validOrganizationSecretID(w http.ResponseWriter, r *http.Request) bool {+ if !isUUID(r.PathValue("org_id")) || !isUUID(r.PathValue("secret_id")) {+ writeProblem(w, invalid("invalid_secret_owner", "path"))+ return false+ }+ w.Header().Set("Cache-Control", "no-store")+ return true+}++func (a *writeAPI) checkOrganizationSecret(w http.ResponseWriter, r *http.Request) {+ if !validOrganizationSecretID(w, r) {+ return+ }+ ctx, cancel := context.WithTimeout(r.Context(), metadataTimeout)+ defer cancel()+ err := secretstore.CheckOrganizationSecret(ctx, a.pool, r.PathValue("org_id"), r.PathValue("secret_id"))+ if errors.Is(err, pgx.ErrNoRows) {+ w.WriteHeader(http.StatusNotFound)+ return+ }+ if err != nil {+ writeProblem(w, transferError(ctx, err))+ return+ }+ w.WriteHeader(http.StatusNoContent)+}++func (a *writeAPI) deleteOrganizationSecret(w http.ResponseWriter, r *http.Request) {+ if !validOrganizationSecretID(w, r) {+ return+ }+ ctx, cancel := context.WithTimeout(r.Context(), metadataTimeout)+ defer cancel()+ if err := secretstore.DeleteOrganizationSecret(ctx, a.pool, r.PathValue("org_id"), r.PathValue("secret_id")); err != nil {+ writeProblem(w, transferError(ctx, err))+ return+ }+ w.WriteHeader(http.StatusNoContent)+}++func organizationRequest(ctx context.Context, w http.ResponseWriter, r *http.Request, shape jsonShape, dest any) bool {+ if !isUUID(r.PathValue("org_id")) {+ writeProblem(w, invalid("org_id_invalid", "org_id"))+ return false+ }+ body := readWriteBody(ctx, w, r)+ if body == nil {+ return false+ }+ defer clear(body)+ if failure := decodeWriteJSON(body, shape, dest); failure != nil {+ writeProblem(w, failure)+ return false+ }+ return true+}++func (a *writeAPI) createOrganizationSecret(w http.ResponseWriter, r *http.Request) {+ ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)+ defer cancel()+ var req struct {+ CreatedBy string `json:"created_by"`+ Secret transferSecret `json:"secret"`+ }+ if !organizationRequest(ctx, w, r, orgCreateJSON, &req) {+ return+ }+ org := r.PathValue("org_id")+ batch := transferRequest{OrgID: org, CreatedBy: req.CreatedBy, Secrets: []transferSecret{req.Secret}}+ if failure := validateSecretBatch(ctx, &batch); failure != nil {+ writeProblem(w, failure)+ return+ }+ s, err := a.encryptSecret(ctx, org, req.CreatedBy, batch.Secrets[0])+ if err == nil {+ err = secretstore.InsertOrganizationSecret(ctx, a.pool, org, s)+ }+ if errors.Is(err, secretstore.ErrOrganizationNameConflict) {+ writeProblem(w, &requestError{status: 409, code: "secret_name_conflict"})+ return+ }+ if err != nil {+ writeProblem(w, transferError(ctx, err))+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.Header().Set("Cache-Control", "no-store")+ w.WriteHeader(http.StatusCreated)+ _ = json.NewEncoder(w).Encode(map[string]string{"id": s.Metadata.ID, "name": s.Metadata.Name})+}++func (a *writeAPI) resolveOrganizationSecrets(w http.ResponseWriter, r *http.Request) {+ ctx, cancel := context.WithTimeout(r.Context(), metadataTimeout)+ defer cancel()+ var req struct {+ Names []string `json:"names"`+ }+ if !organizationRequest(ctx, w, r, orgResolveJSON, &req) {+ return+ }+ if len(req.Names) == 0 || len(req.Names) > 64 {+ writeProblem(w, invalid("invalid_count", "names"))+ return+ }+ seen := make(map[string]bool, len(req.Names))+ for i, name := range req.Names {+ n, err := database.NormalizeName(name)+ if err != nil || seen[n] {+ writeProblem(w, invalid("name_invalid", "names"))+ return+ }+ req.Names[i], seen[n] = n, true+ }+ refs, err := secretstore.ResolveOrganizationSecrets(ctx, a.pool, r.PathValue("org_id"), req.Names)+ if errors.Is(err, pgx.ErrNoRows) {+ writeProblem(w, &requestError{status: 404, code: "secret_not_found"})+ return+ }+ if err != nil {+ writeProblem(w, transferError(ctx, err))+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.Header().Set("Cache-Control", "no-store")+ _ = json.NewEncoder(w).Encode(struct {+ Secrets []secretstore.Reference `json:"secrets"`+ }{refs})+}diff --git a/apps/secret-server/internal/server/write_handlers.go b/apps/secret-server/internal/server/write_handlers.goindex b1339fffc..27f511330 100644--- a/apps/secret-server/internal/server/write_handlers.go+++ b/apps/secret-server/internal/server/write_handlers.go@@ -35,9 +35,16 @@ func writeRoutes(pool *pgxpool.Pool, cipher *encryption.Cipher) http.Handler {mux := http.NewServeMux()const transferPath = "/internal/v1/boxes/{box_id}/secrets"const metadataPath = "/internal/v1/secrets/{secret_id}"+ const orgPath = "/internal/v1/organizations/{org_id}/secrets"+ mux.HandleFunc("POST "+orgPath, a.createOrganizationSecret)+ mux.HandleFunc("GET "+orgPath, a.listOrganizationSecrets)+ mux.HandleFunc("HEAD "+orgPath+"/{secret_id}", a.checkOrganizationSecret)+ mux.HandleFunc("DELETE "+orgPath+"/{secret_id}", a.deleteOrganizationSecret)+ mux.HandleFunc("POST "+orgPath+"/resolve", a.resolveOrganizationSecrets)mux.HandleFunc("POST "+transferPath, a.transfer)mux.HandleFunc("GET "+metadataPath, a.metadata)- mux.HandleFunc(transferPath, writeMethodNotAllowed("POST"))+ mux.HandleFunc("DELETE "+transferPath, a.retireBoxSecrets)+ mux.HandleFunc(transferPath, writeMethodNotAllowed("POST, DELETE"))mux.HandleFunc(metadataPath, writeMethodNotAllowed("GET, HEAD"))mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { problem(w, http.StatusNotFound, "not_found") })return mux@@ -70,45 +77,53 @@ func newSecretID() string {return fmt.Sprintf("%x-%x-%x-%x-%x", id[:4], id[4:6], id[6:8], id[8:10], id[10:])}-func (a *writeAPI) transfer(w http.ResponseWriter, r *http.Request) {- started := time.Now()- result := "failure"- var logBox, logOrg string- var count int- defer func() {- slog.Info("secret transfer", "route", "/internal/v1/boxes/{box_id}/secrets", "box_id", logBox, "org_id", logOrg, "count", count, "result", result, "latency", time.Since(started))- }()- ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)- defer cancel()+func readWriteBody(ctx context.Context, w http.ResponseWriter, r *http.Request) []byte {if r.ContentLength > maxTransferBody {writeProblem(w, &requestError{status: 413, code: "payload_too_large"})- return+ return nil}mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))if err != nil || mediaType != "application/json" {writeProblem(w, &requestError{status: 415, code: "unsupported_media_type"})- return+ return nil}// A context deadline alone cannot interrupt a blocked HTTP body read.deadline, _ := ctx.Deadline()if err := http.NewResponseController(w).SetReadDeadline(deadline); err != nil && !errors.Is(err, http.ErrNotSupported) {writeProblem(w, transferError(ctx, err))- return+ return nil}body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxTransferBody))if !time.Now().Before(deadline) {clear(body)writeProblem(w, transferError(ctx, context.DeadlineExceeded))- return+ return nil}if err != nil {clear(body)var tooLarge *http.MaxBytesErrorif errors.As(err, &tooLarge) {writeProblem(w, &requestError{status: 413, code: "payload_too_large"})- return+ return nil}writeProblem(w, &requestError{status: 400, code: "malformed_json"})+ return nil+ }+ return body+}++func (a *writeAPI) transfer(w http.ResponseWriter, r *http.Request) {+ started := time.Now()+ result := "failure"+ var logBox, logOrg string+ var count int+ defer func() {+ slog.Info("secret transfer", "route", "/internal/v1/boxes/{box_id}/secrets", "box_id", logBox, "org_id", logOrg, "count", count, "result", result, "latency", time.Since(started))+ }()+ ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)+ defer cancel()+ body := readWriteBody(ctx, w, r)+ if body == nil {return}req, failure := decodeTransfer(body)@@ -125,14 +140,12 @@ func (a *writeAPI) transfer(w http.ResponseWriter, r *http.Request) {logBox, logOrg, count = boxID, req.OrgID, len(req.Secrets)secrets := make([]secretstore.Secret, len(req.Secrets))for i, s := range req.Secrets {- id := newSecretID()- identity := encryption.SecretContext{OrganizationID: req.OrgID, SecretID: id, Version: 1, Hosts: s.Hosts, Headers: s.Headers}- envelope, err := a.cipher.Encrypt(ctx, identity, []byte(s.Value))+ prepared, err := a.encryptSecret(ctx, req.OrgID, req.CreatedBy, s)if err != nil {writeProblem(w, transferError(ctx, err))return}- secrets[i] = secretstore.Secret{Metadata: secretstore.Metadata{ID: id, Name: s.Name, NormalizedName: s.Normalized, Hosts: s.Hosts, Headers: s.Headers, Placeholder: s.Placeholder, CreatedBy: req.CreatedBy}, Envelope: envelope}+ secrets[i] = prepared}results, err := secretstore.InsertBoxSecrets(ctx, a.pool, req.OrgID, boxID, secrets, func(ctx context.Context, i int, stored secretstore.Secret) error {return a.checkRetry(ctx, i, req.Secrets[i], stored)@@ -160,6 +173,18 @@ func (a *writeAPI) transfer(w http.ResponseWriter, r *http.Request) {}{entries})}+func (a *writeAPI) encryptSecret(ctx context.Context, org, creator string, s transferSecret) (secretstore.Secret, error) {+ id := newSecretID()+ identity := encryption.SecretContext{OrganizationID: org, SecretID: id, Version: 1, Hosts: s.Hosts, Headers: s.Headers}+ value := []byte(s.Value)+ defer clear(value)+ envelope, err := a.cipher.Encrypt(ctx, identity, value)+ if err != nil {+ return secretstore.Secret{}, err+ }+ return secretstore.Secret{Metadata: secretstore.Metadata{ID: id, Name: s.Name, NormalizedName: s.Normalized, Hosts: s.Hosts, Headers: s.Headers, Placeholder: s.Placeholder, CreatedBy: creator}, Envelope: envelope}, nil+}+func transferError(ctx context.Context, err error) *requestError {if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {return &requestError{status: 503, code: "request_timeout"}@@ -168,6 +193,9 @@ func transferError(ctx context.Context, err error) *requestError {if errors.As(err, &requestErr) {return requestErr}+ if errors.Is(err, secretstore.ErrBoxRetired) {+ return &requestError{status: 409, code: "box_retired"}+ }if errors.Is(err, secretstore.ErrBoxOrgMismatch) {return &requestError{status: 409, code: "box_org_mismatch"}}@@ -281,3 +309,22 @@ func (a *writeAPI) metadata(w http.ResponseWriter, r *http.Request) {CreatedAt time.Time `json:"created_at"`}{m.ID, m.OrganizationID, m.Scope, m.BoxID, m.Name, m.DisabledAt != nil, m.Hosts, m.Headers, m.Placeholder, m.KeyID, m.CreatedBy, m.CreatedAt})}++func (a *writeAPI) retireBoxSecrets(w http.ResponseWriter, r *http.Request) {+ orgID, boxID := r.Header.Get("X-Boxlite-Organization-Id"), r.PathValue("box_id")+ if !isUUID(orgID) {+ writeProblem(w, invalid("org_id_invalid", "org_id"))+ return+ }+ if failure := validateBoxID(boxID); failure != nil {+ writeProblem(w, failure)+ return+ }+ ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)+ defer cancel()+ if err := secretstore.RetireBoxSecrets(ctx, a.pool, orgID, boxID); err != nil {+ writeProblem(w, transferError(ctx, err))+ return+ }+ w.WriteHeader(http.StatusNoContent)+}diff --git a/apps/secret-server/internal/server/write_handlers_test.go b/apps/secret-server/internal/server/write_handlers_test.goindex 9a504c276..d24d5281a 100644--- a/apps/secret-server/internal/server/write_handlers_test.go+++ b/apps/secret-server/internal/server/write_handlers_test.go@@ -13,6 +13,7 @@ import ("net/http""net/http/httptest""os"+ "strconv""strings""sync""testing"@@ -110,6 +111,189 @@ func TestIntegration(t *testing.T) {t.Fatalf("status=%d body=%s, want %d %s", w.Code, w.Body.String(), status, code)}}+ t.Run("organization creation and metadata-only resolution", func(t *testing.T) {+ const otherOrg = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"+ orgPath := func(id string) string { return "/internal/v1/organizations/" + id + "/secrets" }+ request := func(id, suffix, body string) *httptest.ResponseRecorder {+ return call(http.MethodPost, orgPath(id)+suffix, body, "token", "application/json")+ }+ data, err := json.Marshal(map[string]any{"created_by": "creator", "secret": first})+ if err != nil {+ t.Fatal(err)+ }+ assertCode(call(http.MethodPost, orgPath(org), string(data), "wrong", "application/json"), 401, "unauthorized")+ created := request(org, "", string(data))+ var reply map[string]string+ if created.Code != 201 || json.Unmarshal(created.Body.Bytes(), &reply) != nil || len(reply) != 2 || reply["name"] != first.Name || !isUUID(reply["id"]) {+ t.Fatalf("invalid organization secret creation response, status %d", created.Code)+ }+ var encrypted bool+ if err := pool.QueryRow(ctx, "SELECT scope='org' AND box_id IS NULL AND ciphertext <> $2 AND organization_id=$3 FROM secret WHERE id=$1", reply["id"], []byte(first.Value), org).Scan(&encrypted); err != nil || !encrypted {+ t.Fatalf("expected encrypted organization row: %v", err)+ }+ assertCode(request(org, "", strings.Replace(string(data), first.Name, "api_key", 1)), 409, "secret_name_conflict")+ resolve := `{"names":["api_key"]}`+ missing := request(otherOrg, "/resolve", resolve)+ assertCode(missing, 404, "secret_not_found")+ found := request(org, "/resolve", resolve)+ var refs struct {+ Secrets []map[string]json.RawMessage `json:"secrets"`+ }+ if found.Code != 200 || json.Unmarshal(found.Body.Bytes(), &refs) != nil || len(refs.Secrets) != 1 {+ t.Fatal("expected one resolved secret")+ }+ metadata := refs.Secrets[0]+ if len(metadata) != 5 || string(metadata["id"]) != strconv.Quote(reply["id"]) || string(metadata["name"]) != strconv.Quote(first.Name) || metadata["hosts"] == nil || metadata["headers"] == nil || string(metadata["placeholder"]) != strconv.Quote(first.Placeholder) || strings.Contains(found.Body.String(), first.Value) {+ t.Fatal("resolution must return only identity and routing policy")+ }+ if request(otherOrg, "", string(data)).Code != 201 {+ t.Fatal("another organization must be able to reuse the name")+ }+ if _, err := pool.Exec(ctx, "UPDATE secret SET disabled_at=now() WHERE id=$1", reply["id"]); err != nil {+ t.Fatal(err)+ }+ disabled := request(org, "/resolve", resolve)+ if disabled.Code != missing.Code || disabled.Body.String() != missing.Body.String() {+ t.Fatal("unavailable names must be indistinguishable")+ }+ resource := orgPath(org) + "/" + reply["id"]+ get := func(path string) *httptest.ResponseRecorder { return call(http.MethodGet, path, "", "token", "") }+ for _, method := range []string{http.MethodGet, http.MethodHead, http.MethodDelete} {+ target := resource+ if method == http.MethodGet {+ target = orgPath(org) + "?limit=1"+ }+ assertCode(call(method, target, "", "wrong", ""), 401, "unauthorized")+ }+ list := get(orgPath(org) + "?limit=1")+ var page struct {+ Secrets []map[string]json.RawMessage `json:"secrets"`+ }+ if list.Code != 200 || list.Header().Get("Cache-Control") != "no-store" || json.Unmarshal(list.Body.Bytes(), &page) != nil || len(page.Secrets) != 1 {+ t.Fatal("expected one organization secret")+ }+ want, err := json.Marshal(map[string]any{"id": reply["id"], "name": first.Name, "hosts": first.Hosts, "headers": first.Headers, "placeholder": first.Placeholder})+ if err != nil {+ t.Fatal(err)+ }+ if got, err := json.Marshal(page.Secrets[0]); err != nil || !bytes.Equal(got, want) {+ t.Fatal("expected exactly the stored identity, hosts, header templates and placeholder")+ }+ empty := get(orgPath(org) + "?limit=1&after=" + reply["id"])+ if empty.Code != 200 || strings.TrimSpace(empty.Body.String()) != `{"secrets":[]}` {+ t.Fatal("expected empty final page")+ }+ assertCode(get(orgPath(org)+"?limit=1002"), 422, "invalid_page")+ assertCode(get(orgPath(org)+"?limit=1&after=bad"), 422, "invalid_page")+ head := func(path string) int { return call(http.MethodHead, path, "", "token", "").Code }+ remove := func(path string) int { return call(http.MethodDelete, path, "", "token", "").Code }+ foreign := orgPath(otherOrg) + "/" + reply["id"]+ if head(foreign) != 404 || remove(foreign) != 204 || head(resource) != 204 {+ t.Fatal("foreign deletion changed the owner")+ }+ private := call(http.MethodPost, "/internal/v1/boxes/BoxListScope/secrets", encode(org, []wireSecret{second}), "token", "application/json")+ var privateID string+ if private.Code != 201 || pool.QueryRow(ctx, "SELECT id::text FROM secret WHERE box_id='BoxListScope'").Scan(&privateID) != nil {+ t.Fatal("could not create private secret")+ }+ privatePath := orgPath(org) + "/" + privateID+ if head(privatePath) != 404 || remove(privatePath) != 204 || get(orgPath(org)+"?limit=100").Body.String() != list.Body.String() {+ t.Fatal("box-owned secret appeared in organization management")+ }+ var exists bool+ if err := pool.QueryRow(ctx, "SELECT EXISTS (SELECT FROM secret WHERE id=$1)", privateID).Scan(&exists); err != nil || !exists {+ t.Fatal("box-owned secret was deleted")+ }+ if remove(resource) != 204 || remove(resource) != 204 || head(resource) != 404 {+ t.Fatal("expected idempotent scoped deletion")+ }+ recreated := request(org, "", string(data))+ var replacement map[string]string+ if recreated.Code != 201 || json.Unmarshal(recreated.Body.Bytes(), &replacement) != nil || replacement["id"] == reply["id"] || remove(resource) != 204 || request(org, "/resolve", resolve).Code != 200 {+ t.Fatal("stale deletion affected recreated name")+ }++ })+ t.Run("organization secret request validation", func(t *testing.T) {+ const collection = "/internal/v1/organizations/" + org + "/secrets"+ const badOwner = "/internal/v1/organizations/bad/secrets"+ const resolve = collection + "/resolve"+ tooManyNames := `{"names":[` + strings.Repeat(`"a",`, 64) + `"a"]}`+ for _, tc := range []struct {+ name, method, path, body string+ status int+ code, field string+ }{+ {"list invalid owner", "GET", badOwner + "?limit=1", "", 422, "org_id_invalid", "org_id"},+ {"create invalid owner", "POST", badOwner, "{}", 422, "org_id_invalid", "org_id"},+ {"check invalid ID", "HEAD", collection + "/bad", "", 422, "", ""},+ {"delete invalid owner", "DELETE", badOwner + "/" + org, "", 422, "invalid_secret_owner", "path"},+ {"create unexpected field", "POST", collection, `{"org_id":"other"}`, 400, "malformed_json", ""},+ {"create missing creator", "POST", collection, `{"secret":{}}`, 422, "created_by_invalid", "created_by"},+ {"resolve oversize body", "POST", resolve, strings.Repeat("x", maxTransferBody+1), 413, "payload_too_large", ""},+ {"resolve unexpected field", "POST", resolve, `{"name":"a"}`, 400, "malformed_json", ""},+ {"resolve empty batch", "POST", resolve, `{"names":[]}`, 422, "invalid_count", "names"},+ {"resolve over 64 names", "POST", resolve, tooManyNames, 422, "invalid_count", "names"},+ {"resolve empty name", "POST", resolve, `{"names":[""]}`, 422, "name_invalid", "names"},+ {"resolve equivalent names", "POST", resolve, `{"names":["api-key","API_KEY"]}`, 422, "name_invalid", "names"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ w := call(tc.method, tc.path, tc.body, "token", "application/json")+ if w.Code != tc.status {+ t.Fatalf("status = %d, want %d", w.Code, tc.status)+ }+ if tc.method == http.MethodHead {+ return+ }+ var problem struct{ Code, Field string }+ if err := json.Unmarshal(w.Body.Bytes(), &problem); err != nil || problem.Code != tc.code || problem.Field != tc.field {+ t.Fatalf("problem = %+v, error = %v; want %s %q", problem, err, tc.code, tc.field)+ }+ })+ }+ })+ t.Run("retirement is scoped and prevents delayed transfers", func(t *testing.T) {+ const otherOrg = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"+ forget := func(boxID, orgID string) *httptest.ResponseRecorder {+ r := httptest.NewRequest(http.MethodDelete, "/internal/v1/boxes/"+boxID+"/secrets", nil)+ r.Header.Set("Authorization", "Bearer token")+ r.Header.Set("X-Boxlite-Organization-Id", orgID)+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, r)+ return w+ }+ const a, b = "BoxRetire001", "BoxRetire002"+ assertCode(forget(a, ""), 422, "org_id_invalid")+ assertCode(forget("bad", org), 422, "box_id_invalid")+ write := func(id string) *httptest.ResponseRecorder {+ return call(http.MethodPost, "/internal/v1/boxes/"+id+"/secrets", encode(org, []wireSecret{second}), "token", "application/json")+ }+ if write(a).Code != 201 || write(b).Code != 201 {+ t.Fatal("box transfer failed")+ }+ if forget(a, otherOrg).Code != 204 || write(a).Code != 200 {+ t.Fatal("foreign cleanup affected owner")+ }+ for range 2 {+ if forget(a, org).Code != 204 {+ t.Fatal("repeated cleanup failed")+ }+ }+ assertCode(write(a), 409, "box_retired")+ var remaining []string+ rows, err := pool.Query(ctx, "SELECT box_id FROM secret WHERE box_id=ANY($1) ORDER BY box_id", []string{a, b})+ if err != nil {+ t.Fatal(err)+ }+ remaining, err = pgx.CollectRows(rows, pgx.RowTo[string])+ if err != nil || len(remaining) != 1 || remaining[0] != b {+ t.Fatalf("unexpected remaining box owners: %v", remaining)+ }+ if forget("BoxLateWrite", org).Code != 204 {+ t.Fatal("retirement before transfer failed")+ }+ assertCode(write("BoxLateWrite"), 409, "box_retired")+ })assertCode(call(http.MethodPost, path, "not json", "wrong", "application/json"), 401, "unauthorized")assertCode(call(http.MethodPost, path, "{}", "token", "text/plain"), 415, "unsupported_media_type")assertCode(post(`{"secrets":[]}`), 400, "malformed_json")@@ -201,7 +385,7 @@ func TestIntegration(t *testing.T) {status int}{{http.MethodGet, "/internal/v1/missing", "not_found", "", 404},- {http.MethodGet, path, "method_not_allowed", "POST", 405},+ {http.MethodGet, path, "method_not_allowed", "POST, DELETE", 405},{http.MethodPost, "/internal/v1/secrets/" + firstID, "method_not_allowed", "GET, HEAD", 405},} {w := call(tc.method, tc.path, "", "token", "")@@ -419,19 +603,45 @@ func TestIntegration(t *testing.T) {}})- t.Run("metadata masks database errors", func(t *testing.T) {+ t.Run("secret routes mask database errors", func(t *testing.T) {closed, err := pgxpool.NewWithConfig(ctx, pool.Config())if err != nil {t.Fatal(err)}closed.Close()- r := httptest.NewRequest(http.MethodGet, "/internal/v1/secrets/"+firstID, nil)- r.Header.Set("Authorization", "Bearer token")- w := httptest.NewRecorder()- routes(config, closed.Ping, nil, nil, writeRoutes(closed, cipher)).ServeHTTP(w, r)- var problem struct{ Code, Title string }- if err := json.Unmarshal(w.Body.Bytes(), &problem); err != nil || w.Code != 500 || problem.Code != "internal_error" || problem.Title != http.StatusText(500) {- t.Fatalf("metadata: status=%d problem=%+v decode error=%v", w.Code, problem, err)+ handler := routes(config, closed.Ping, nil, nil, writeRoutes(closed, cipher))+ const collection = "/internal/v1/organizations/" + org + "/secrets"+ create, err := json.Marshal(map[string]any{"created_by": "creator", "secret": first})+ if err != nil {+ t.Fatal(err)+ }+ for _, tc := range []struct{ method, path, body string }{+ {"GET", "/internal/v1/secrets/" + firstID, ""},+ {"GET", collection + "?limit=1", ""},+ {"HEAD", collection + "/" + firstID, ""},+ {"DELETE", collection + "/" + firstID, ""},+ {"POST", collection, string(create)},+ {"POST", collection + "/resolve", `{"names":["api_key"]}`},+ {"DELETE", path, ""},+ } {+ t.Run(tc.method+" "+tc.path, func(t *testing.T) {+ r := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))+ r.Header.Set("Authorization", "Bearer token")+ r.Header.Set("Content-Type", "application/json")+ r.Header.Set("X-Boxlite-Organization-Id", org)+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, r)+ if w.Code != 500 {+ t.Fatalf("status = %d, want 500", w.Code)+ }+ if tc.method == http.MethodHead {+ return+ }+ var problem struct{ Code, Title string }+ if err := json.Unmarshal(w.Body.Bytes(), &problem); err != nil || problem.Code != "internal_error" || problem.Title != http.StatusText(500) {+ t.Fatalf("problem = %+v, decode error = %v", problem, err)+ }+ })}})diff --git a/apps/secret-server/internal/server/write_validation.go b/apps/secret-server/internal/server/write_validation.goindex bc655d6db..a8dcccbae 100644--- a/apps/secret-server/internal/server/write_validation.go+++ b/apps/secret-server/internal/server/write_validation.go@@ -49,6 +49,8 @@ const (secretJSONhostsJSONheadersJSON+ orgCreateJSON+ orgResolveJSON)// inspectJSON checks duplicates everywhere and exact field names on request objects.@@ -64,7 +66,7 @@ func inspectJSON(dec *json.Decoder, shape jsonShape) error {return nil}switch shape {- case transferJSON, secretJSON, headersJSON:+ case transferJSON, secretJSON, headersJSON, orgCreateJSON, orgResolveJSON:if token != json.Delim('{') {return fmt.Errorf("expected an object")}@@ -80,6 +82,19 @@ func inspectJSON(dec *json.Decoder, shape jsonShape) error {}child := stringJSONswitch shape {+ case orgCreateJSON:+ switch name {+ case "created_by":+ case "secret":+ child = secretJSON+ default:+ return fmt.Errorf("unknown organization secret field")+ }+ case orgResolveJSON:+ if name != "names" {+ return fmt.Errorf("unknown resolution field")+ }+ child = hostsJSONcase transferJSON:switch name {case "org_id", "created_by":@@ -167,24 +182,32 @@ func validJSONUnicode(body []byte) bool {}func decodeTransfer(body []byte) (transferRequest, *requestError) {- bad := &requestError{status: http.StatusBadRequest, code: "malformed_json"}+ var req transferRequest+ if failure := decodeWriteJSON(body, transferJSON, &req); failure != nil {+ return req, failure+ }+ if len(req.Secrets) == 0 {+ return req, &requestError{status: 400, code: "malformed_json"}+ }+ return req, nil+}++func decodeWriteJSON(body []byte, shape jsonShape, target any) *requestError {+ bad := &requestError{status: 400, code: "malformed_json"}if !validJSONUnicode(body) {- return transferRequest{}, bad+ return bad}dec := json.NewDecoder(bytes.NewReader(body))- if err := inspectJSON(dec, transferJSON); err != nil {- return transferRequest{}, bad+ if err := inspectJSON(dec, shape); err != nil {+ return bad}if _, err := dec.Token(); err != io.EOF {- return transferRequest{}, bad+ return bad}- dec = json.NewDecoder(bytes.NewReader(body))- dec.DisallowUnknownFields()- var req transferRequest- if err := dec.Decode(&req); err != nil || len(req.Secrets) == 0 {- return transferRequest{}, bad+ if err := json.Unmarshal(body, target); err != nil {+ return bad}- return req, nil+ return nil}func isUUID(s string) bool {@@ -228,6 +251,13 @@ func headerToken(s string) bool {}func validateTransfer(ctx context.Context, boxID string, req *transferRequest) *requestError {+ if failure := validateBoxID(boxID); failure != nil {+ return failure+ }+ return validateSecretBatch(ctx, req)+}++func validateBoxID(boxID string) *requestError {if len(boxID) != 12 {return invalid("box_id_invalid", "box_id")}@@ -236,6 +266,10 @@ func validateTransfer(ctx context.Context, boxID string, req *transferRequest) *return invalid("box_id_invalid", "box_id")}}+ return nil+}++func validateSecretBatch(ctx context.Context, req *transferRequest) *requestError {if !isUUID(req.OrgID) {return invalid("org_id_invalid", "org_id")}diff --git a/apps/secret-server/tests/secret-list-api.sh b/apps/secret-server/tests/secret-list-api.shnew file mode 100644index 000000000..0d0bb1378--- /dev/null+++ b/apps/secret-server/tests/secret-list-api.sh@@ -0,0 +1,48 @@+#!/usr/bin/env bash+set -euo pipefail++# Supply a fresh disposable database: startup binds its encrypted canary to this run's key.+: "${SECRET_TEST_DATABASE_URL:?set SECRET_TEST_DATABASE_URL to a fresh PostgreSQL database}"+cd "$(dirname "$0")/../../.."+umask 077+work=$(mktemp -d)+pid=''+cleanup() {+ if [[ -n "$pid" ]]; then+ kill "$pid" 2>/dev/null || true+ wait "$pid" 2>/dev/null || true+ fi+ rm -rf -- "$work"+}+trap cleanup EXIT+trap 'exit 130' INT+trap 'exit 143' TERM++(cd apps/secret-server && GOWORK=off go build -o "$work/secret-server" ./cmd/secret-server)+token=$(openssl rand -hex 32)+key=$(openssl rand -base64 32)+port=${SECRET_LIST_TEST_PORT:-18785}+export SECRET_SERVER_URL="http://127.0.0.1:$port" SECRET_SERVER_DEV_TOKEN="$token"+ENVIRONMENT=local SECRET_SERVER_ROLE=write SECRET_SERVER_AUTH_MODE=dev PORT="$port" \+ DATABASE_URL="$SECRET_TEST_DATABASE_URL" SECRET_MASTER_KEY_ID=env:test SECRET_MASTER_KEY_BASE64="$key" \+ "$work/secret-server" &+pid=$!+deadline=$((SECONDS + 60))+until curl --fail --silent --max-time 1 "$SECRET_SERVER_URL/ready" >/dev/null; do+ if ! kill -0 "$pid" 2>/dev/null || (( SECONDS >= deadline )); then+ echo 'Secret Server exited or failed to become ready within 60 seconds' >&2+ exit 1+ fi+ sleep 1+done++cd apps+yarn nx run api:test --skip-nx-cache --runInBand --testPathPatterns=boxlite-secret.controller.spec \+ --verbose --json --outputFile="$work/jest.json"+jq -er --arg metadata "lists stored routing metadata through the public API for only the caller’s organization secrets" \+ --arg pagination 'returns all 101 organization secrets in default pages of 100 and 1' '+ [.testResults[].assertionResults[]] as $tests |+ ($metadata, $pagination) as $name |+ [$tests[] | select(.title == $name) | .status] |+ if . == ["passed"] then "PASS " + $name else error("Required test did not pass: " + $name) end+' "$work/jest.json"diff --git a/docs/contributing/architecture/platform/api.md b/docs/contributing/architecture/platform/api.mdindex 4f8f052fa..ead9f0aab 100644--- a/docs/contributing/architecture/platform/api.md+++ b/docs/contributing/architecture/platform/api.md@@ -713,8 +713,90 @@ 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;-bounded cleanup requires the separate [lifecycle contract tracked in #2865](https://github.com/boxlite-ai/boxlite/issues/2865).+or upstream errors.++Use `POST /api/v1/secrets` with the organization's `write:secrets` permission to+save a named credential. Supply `name`, `value`, `hosts`, `headers` and optionally+`placeholder`. The response contains the ID and name. Each entry in the Box create+request's `secrets` array can be an inline secret or a reference such as+`{"secret":"openai"}`. Resolution uses the authenticated organization and saves the+ID and routing policy on the new Box. Multiple Boxes can reference the same row.++Use `GET /api/v1/secrets` with `read:secrets` to list the authenticated+organization's named secrets. Each entry contains `id`, `name`, the stored+`hosts` list, the `headers` templates with their literal `{value}` marker, and+the stored `placeholder`. Listing reads these metadata fields without decrypting+the credential.++Use `pageSize` (1–100, default 100) and pass the returned+`next_page_token` as `pageToken` for the next page.++Use `DELETE /api/v1/secrets/{secret_id}` with `write:secrets` to delete by ID.++| Condition | HTTP result |+| --- | --- |+| A Box still references the ID, including a stopped Box or one awaiting destruction | 409 |+| The ID is unknown, belongs to another organization, or identifies a Box-owned secret | 404 |+| Secret Server confirms removal, or the owning organization repeats a completed deletion | 204 |++Once the last referencing Box is destroyed, the API records the ID and requests removal from Secret Server.+The API retries pending deliveries every 30 seconds. Repeating a deletion preserves any new secret created under the same name.++Deletion reads Box references under `READ COMMITTED` so it sees any Box that committed while it waited for the lock.+For Box writes under a fixed snapshot, the trigger tests the retirement table's unique key, which also detects newer committed deletions.+If a stale binding returns 409, retry Box creation to resolve the name again.++```mermaid+sequenceDiagram+ participant C as Box creator+ participant A as Hosted API+ participant D as API database+ participant S as Secret Server+ alt Box binding commits first+ C->>A: Create Box using the named secret+ A->>D: Lock secret ID and commit Box binding+ A->>D: Delete locks the same ID and finds the Box+ Note over A: Return 409+ else Deletion commits first+ A->>D: Lock ID, verify no Box uses it, commit retirement+ C->>A: Publish a Box with the previously resolved ID+ A->>D: Acquire lock and check retirement+ Note over A: Reject the stale Box binding+ A->>S: Delete by organization and immutable ID+ alt Response received+ S-->>A: Removal confirmed+ A->>D: Record completion+ else Response lost+ A->>D: Keep the pending removal+ A->>S: Retry the same organization and ID+ S-->>A: Removal confirmed+ A->>D: Record completion+ end+ end+```++Python and Node callers can put `{"secret": "openai"}` next to inline secrets in+the existing `secrets` array. Go callers can combine `WithSecretReference("openai")`+and `WithSecret(...)`. The C options builder provides `boxlite_options_add_secret_reference`.++Rust callers pass inline `Secret` values directly in `BoxOptions.secrets`.+For hosted creation, `options.with_secret_reference("openai")` appends a reference+to the saved organization secret. Both `create` and `get_or_create` use the same+ordered entries when creating the Box.++An inline transfer reserves the Box ID in the API database before writing the+encrypted values. Box insertion consumes that reservation in its transaction.+A rolled-back creation leaves a reservation for recovery.++Stop and restart keep the Box's secrets. Confirmed destruction or permanent+deletion of the API Box row queues cleanup in the same transaction, including+when the seven-day error sweep removes a Box.++Each API instance checks for cleanup every 30 seconds and claims+at most one due task per check. Secret Server retires the Box's private records.+The API retries failed deliveries.++Shared organization secrets remain usable by other Boxes.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 ordiff --git a/docs/contributing/investigations/2026-11-30-organization-secret-reuse.md b/docs/contributing/investigations/2026-11-30-organization-secret-reuse.mdnew file mode 100644index 000000000..4b428d8a8--- /dev/null+++ b/docs/contributing/investigations/2026-11-30-organization-secret-reuse.md@@ -0,0 +1,115 @@+**Status:** Implemented on the integration baseline. Hosted two-Box acceptance remains pending.++# Named organization secrets and Box-owned cleanup++A hosted client can save a credential once and reference its name in several Boxes. A value supplied during Box creation belongs to that Box until permanent destruction.++## Behavior before this change++The hosted API transfers inline values before inserting the Box. If the insert fails or the API exits after transfer, the Secret Server may retain the encrypted records without an owner in the API database. A timeout also leaves the remote commit outcome unknown. See [Box creation](https://github.com/boxlite-ai/boxlite/blob/fa986d2737731da0e143ce988a78b799c101d862/apps/api/src/box/services/box.service.ts) and the [inline transfer design](https://github.com/boxlite-ai/boxlite/issues/2736).++The [Secret Server schema](https://github.com/boxlite-ai/boxlite/blob/fa986d2737731da0e143ce988a78b799c101d862/apps/secret-server/internal/database/migrations/00001_initial.sql) already defines organization ownership, immutable policies and a per-organization unique index. The [credential issuer](https://github.com/boxlite-ai/boxlite/blob/fa986d2737731da0e143ce988a78b799c101d862/apps/api/src/box/services/secret-credential.service.ts) already binds an explicit set of IDs to a Box, its organization and its assigned Runner.++## Choosing how Boxes share a credential++Box A and Box B must use one organization-owned value. Removing A must preserve B’s access, and neither Box should receive plaintext in its environment.++| Method | Projects or existing behavior | Trade-off | Decision |+| --- | --- | --- | --- |+| Keep inline creation only | [BoxLite inline transfer](https://github.com/boxlite-ai/boxlite/issues/2736) | Callers must resubmit the value for each Box. Each transfer produces a separate Box-owned record. | Retain for private credentials. It cannot implement a shared name. |+| Copy a shared value for each consumer | The [CSI driver’s optional sync](https://secrets-store-csi-driver.sigs.k8s.io/topics/sync-as-kubernetes-secret) materializes a Kubernetes Secret. | An analogous per-Box copy would add ciphertext, writes and cleanup for each consumer. | Reject per-Box copies. |+| Resolve an external name at each start | The [CSI driver](https://secrets-store-csi-driver.sigs.k8s.io/concepts.html#secretproviderclass) uses a namespace-scoped provider configuration at mount time. ECS can fetch the [current secret version](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/secrets-envvar-secrets-manager.html). | Startup must handle changes in what the name selects. The guest-visible volume or environment also conflicts with proxy-only use. | Adapt name scoping. Keep the resolved identity across restarts. |+| Resolve once and grant the stored ID | ECS can select a [specific secret version](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/secrets-envvar-secrets-manager.html). BoxLite’s [fetch service](https://github.com/boxlite-ai/boxlite/blob/d9015c980be210c4784e0289db036635ff15dc8c/apps/secret-server/internal/fetch/handler.go#L118-L146) already checks tenant and ownership for every granted ID. | Admission requires one metadata lookup. Subsequent grants reuse the saved IDs and the deployed policy model. | **Pick.** Share one encrypted row and keep the value behind Runner authentication and the host proxy. |++## Creating and using a shared credential++1. An authorized caller sends `POST /api/v1/secrets` with a name, value, hosts, headers and optional placeholder. Derive the organization and creator from the authenticated context. Add a dedicated organization write permission for provisioning shared credentials. Apply the existing suspension checks and enforce scope for restricted API keys.+2. The API calls the authenticated write role at `POST /internal/v1/organizations/{org_id}/secrets`. Reuse the inline write validator, placeholder default and single-value encryption. Insert one row with organization scope and a null Box ID. Return 201 with ID and name. A normalized-name conflict in that organization returns 409.+3. In a Box create request, each array element is either a complete inline secret or an object containing only a secret name. Reject ambiguous objects, client-selected IDs and per-reference policy overrides. Resolve references with one authenticated `POST /internal/v1/organizations/{org_id}/secrets/resolve`. Select only IDs, names and injection policy for active organization rows. A missing, disabled or foreign name produces the same failure for the whole batch.+4. Validate the combined policy before writing inline values. Check the aggregate count, normalized names and case-insensitive host/header collisions across both variants. Persist the canonical name, ID and policy for each entry in request order. Named references require the hosted secret store. The existing inline feature flag and local SDK inline behavior retain their defaults.+5. The API issues a grant for the stored IDs. The Runner authenticates to the existing fetch endpoint. The fetch service validates the single-use credential and every row's ownership before decryption. A subsequent create job that needs credentials obtains a new grant for the original IDs. Guest processes use placeholders, and the host proxy applies the configured policy.++For example, save an organization secret named `openai`. Create Box A with an inline service credential and `{"secret":"openai"}` in the same array. Create Box B with just the reference. Each Box has its own credential grant. A Box creator can use the shared credential only through its saved routing policy.++```mermaid+sequenceDiagram+ participant C as SDK+ participant A as Hosted API+ participant S as Secret Server+ participant R as Assigned Runner+ C->>A: Create Box with inline entry and name+ A->>S: Resolve name in caller organization+ S-->>A: ID, canonical name and injection policy+ A->>S: Store inline entry under Box ID+ S-->>A: Inline ID+ A->>R: CREATE_BOX with one-use credential+ R->>S: Fetch with identity and credential+ S->>A: Redeem credential for assigned Runner+ A-->>S: Organization, Box and authorized IDs+ S-->>R: Values and policies for this grant+```++Use a distinct reference representation at the SDK boundary, preserving existing inline constructors and serialization. Capture requests from public remote SDK entry points for omitted, inline, named and mixed inputs. Local backends must reject a hosted reference before starting a Box. Dynamic attachment, rotation and name resolution on restart are outside this contract.++## Cleanup ownership and recovery++Before the first inline transfer, durably insert a creation intent keyed by organization and server-assigned Box ID, containing no value. The active creator locks that row, checks it is still pending, transfers the values and finalizes the intent in the same API transaction that inserts the Box. Reuse the transaction that enforces creation limits and runs the persistence callback. Bound the remote call and lock hold time. A rollback leaves the pre-existing intent visible to recovery.++A worker claims abandoned intents using row locks and skips locked rows. Recheck eligibility in the transaction that changes the intent to cleanup pending. If recovery claims an abandoned intent first, a resumed creator must fail before writing or publishing the Box. A retry that legitimately owns a pending attempt retains it. Age alone cannot authorize deletion. Once a Box exists, enqueue cleanup in the same transaction that records confirmed destruction, including automatic destruction. Also enqueue when the API permanently deletes the Box row, including the seven-day sweep of stale destruction errors. A retained error row keeps its secrets. Keep ownership through stop, restart, logical delete and recoverable errors.++`DELETE /internal/v1/boxes/{box_id}/secrets` accepts the trusted API's organization context. In a single transaction take the Box write lock, record a durable retirement marker for that organization and Box, and delete rows matching organization, Box and Box scope. Under the same lock, inline writes must check the marker before inserting. This prevents a delayed POST from recreating records after an apparently successful DELETE. Return 204 on repeated cleanup. Organization records never qualify. The worker acknowledges cleanup and clears the destroyed Box's references only after success. Persist retry scheduling with capped backoff so an API or Secret Server restart can resume delivery.++The API recovers abandoned transfers by organization and Box ID from its committed creation intents. Retired Box IDs must remain unique.++### Concurrent creation and cleanup++The API database decides which attempt may publish the Box. The Secret Server database serializes retirement with writes for the same Box.++```mermaid+sequenceDiagram+ participant C as Creator+ participant D as API database+ participant W as Cleanup worker+ participant S as Secret Server+ C->>D: Commit intent for organization and Box+ C->>D: Lock pending intent in Box insertion transaction+ C->>S: Send inline write+ W->>D: Try to claim abandoned intent, skip locked row+ alt Creator commits+ C->>D: Insert Box and finalize intent atomically+ W->>D: Recheck ownership, preserve recoverable Box+ D->>D: On confirmed destruction, enqueue cleanup atomically+ else Creator rolls back or dies+ D->>D: Release row lock, keep committed intent+ W->>D: Recheck eligibility and claim abandoned intent+ C->>D: A resumed creator observes lost ownership and stops+ end+ W->>S: DELETE using trusted organization and Box+ S->>S: Lock Box, record retirement and delete private rows, commit+ opt Earlier POST reaches store after retirement+ S->>S: Lock Box, observe retirement, reject insertion+ end+ alt Worker receives 204+ W->>D: Acknowledge cleanup and clear destroyed Box references+ else Response lost or service unavailable+ W->>D: Retain pending task and schedule retry+ end+```++| Method | Relevant precedent | Decision |+| --- | --- | --- |+| Synchronous cleanup in the create error handler | Existing transfer before Box insertion | A process exit can skip the handler and a late POST can follow deletion. |+| Durable cleanup intent and idempotent delivery | [Transactional outbox](https://microservices.io/patterns/data/transactional-outbox.html), [Kubernetes finalizers](https://kubernetes.io/docs/concepts/overview/working-with-objects/finalizers/) | Persist eligibility with the lifecycle transition so retries survive crashes. |+| Serialize writes and retirement | [Box write store](https://github.com/boxlite-ai/boxlite/pull/3103), [PostgreSQL advisory locks](https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS) | Reuse the existing per-Box transaction lock. Persist retirement because a lock ends at commit. |++## Validation++| Boundary | Planned proof |+| --- | --- |+| Secret Server and PostgreSQL | Same-org normalized collisions return 409, different organizations can use the same name, unauthorized writes fail, metadata resolution excludes encrypted and plaintext value fields. |+| Public API and SDK | Verify actual request bodies and permissions for named and mixed inputs. A foreign name and a missing name have identical public responses. A failed mixed create publishes no Box or credential. |+| Cleanup and concurrency | Pause the transfer and race recovery, kill the creator after the remote commit, lose the DELETE response, retry after service recovery and deliver an old write after cleanup. Observe final rows from a second connection. |+| Existing owners | Stop, restart and failed destruction preserve both references. Exercise automatic and explicit destruction and cross-tenant or cross-Box cleanup attempts. |+| Two live Boxes | Use a controlled HTTPS upstream that returns only an authentication verdict. Verify both credentials on A and the shared credential on B. Check guest environment and output for placeholders and absence of values. Repeat after A restarts. Delete A, observe its private row disappear, and make a fresh authenticated request from B. |++The live test depends on the [inline writer](https://github.com/boxlite-ai/boxlite/pull/3103), [fetch service](https://github.com/boxlite-ai/boxlite/pull/3024) and [Runner fetch client](https://github.com/boxlite-ai/boxlite/pull/2747). The Runner and service must use the same fetch path. The service integration test exercises mixed grants and private retirement against PostgreSQL. The two-Box case also requires a deployment of this change with an attested Runner, two organizations and a working HTTPS preview.diff --git a/docs/reference/nodejs/README.md b/docs/reference/nodejs/README.mdindex a0c4a150d..0189d6dba 100644--- a/docs/reference/nodejs/README.md+++ b/docs/reference/nodejs/README.md@@ -630,7 +630,7 @@ interface SimpleBoxOptions {volumes?: JsVolumeSpec[]; // Volume mounts (managedVolume or hostPath)network?: NetworkSpec;ports?: PortSpec[]; // Port mappings- secrets?: Secret[];+ secrets?: Array<Secret | { secret: string }>; // Named references use the hosted organization.advanced?: {capabilities?: {add?: string[]; // Add Linux capabilitiesdiff --git a/docs/reference/python/README.md b/docs/reference/python/README.mdindex 6ff31f936..03e7005cc 100644--- a/docs/reference/python/README.md+++ b/docs/reference/python/README.md@@ -231,7 +231,7 @@ Configuration options for creating a box.| `volumes` | `List[Tuple \| Dict]` | `[]` | Volume mounts; tuple = host bind, dict = `managed_volume` or `host_path` || `network` | `NetworkSpec \| None` | `None` | Structured network configuration. Omit for default enabled networking. || `ports` | `List[Tuple \| Dict]` | `[]` | Local TCP forwarding; omit `host_port` in a dict for automatic allocation |-| `secrets` | `List[Secret]` | `[]` | Secrets rendered into configured headers of outbound HTTPS requests |+| `secrets` | `list` | `[]` | Inline `Secret` objects and hosted organization references such as `{"secret": "openai"}` for outbound HTTPS headers || `advanced` | `AdvancedBoxOptions \| None` | `None` | Expert-only options, including `capabilities.add` and `capabilities.drop` || `auto_delete` | `int \| None` | `None` | `0` keeps the box after stop; above `0`, a REST runtime deletes it that many seconds after stop and a local runtime at stop. `None` keeps the runtime's default (`auto_remove` locally) || `auto_remove` | `bool` | `True` | Deprecated: use `auto_delete`. Auto cleanup when stopped |diff --git a/docs/reference/rust/README.md b/docs/reference/rust/README.mdindex 3b56b4a08..0fa1aee63 100644--- a/docs/reference/rust/README.md+++ b/docs/reference/rust/README.md@@ -99,7 +99,7 @@ let runtime = BoxliteRuntime::default_runtime();| `default_runtime` | `fn default_runtime() -> &'static Self` | Get/create global singleton || `try_default_runtime` | `fn try_default_runtime() -> Option<&'static Self>` | Get global if initialized || `init_default_runtime` | `fn init_default_runtime(options: BoxliteOptions) -> BoxliteResult<()>` | Initialize global with options |-| `create` | `async fn create(&self, options: BoxOptions, name: Option<String>) -> BoxliteResult<LiteBox>` | Create a new box |+| `create` | `async fn create(&self, options: CreateBoxOptions<impl Into<CreateSecret>>, name: Option<String>) -> BoxliteResult<LiteBox>` | Create a new box || `get` | `async fn get(&self, id_or_name: &str) -> BoxliteResult<Option<LiteBox>>` | Get box by ID or name || `get_info` | `async fn get_info(&self, id_or_name: &str) -> BoxliteResult<Option<BoxInfo>>` | Get box info without handle || `list_info` | `async fn list_info(&self) -> BoxliteResult<Vec<BoxInfo>>` | List all boxes |@@ -1074,7 +1074,7 @@ pub struct BoxOptions {/// Inbound reachability of exposed servicespub inbound_network: NetworkSpec,- /// Secrets injected into a request header on outbound HTTPS requests+ /// Inline secret valuespub secrets: Vec<Secret>,/// Port mappings@@ -1096,6 +1096,20 @@ pub struct BoxOptions {}```+`BoxOptions.secrets` accepts inline `Secret` values directly. On a hosted+runtime, call `with_secret_reference(name)` once for each saved organization+secret. Both `create` and `get_or_create` accept the result. Each call appends+a reference in order and the SDK sends the entries together when creating the Box.++```rust+let options = boxlite::BoxOptions {+ secrets: vec![inline_secret],+ ..Default::default()+};+let options = options.with_secret_reference("openai");+let worker = runtime.create(options, Some("worker".into())).await?;+```+#### Example```rustdiff --git a/make/help.mk b/make/help.mkindex 0522502e7..d73b1cde3 100644--- a/make/help.mk+++ b/make/help.mk@@ -125,6 +125,7 @@ help:@echo " make test:apps:proxy - Run proxy unit tests (FILTER=<pattern>)"@echo " make test:apps:secret-server - Run Secret Server Go tests with the race detector"@echo " make test:apps:secret-server:credential-api - Test the pinned credential API with Secret Server"+ @echo " make test:apps:secret-server:secret-list-api - Test the public secret list against Secret Server and PostgreSQL"@echo " make test:apps:secret-server:integration - Test Secret Server against PostgreSQL (set SECRET_TEST_DATABASE_URL)"@echo " make test:apps:mdeploy - Type-check and test deployment scripts"@echo " make test:apps:mbuild - Type-check and test image publication scripts"diff --git a/make/test.mk b/make/test.mkindex 6df2bc8e7..7e7e3f5ab 100644--- a/make/test.mk+++ b/make/test.mk@@ -845,6 +845,10 @@ _require-secret-test-database:test\:apps\:secret-server\:integration: _require-secret-test-database@cd apps/secret-server && GOWORK=off go test -race -count=1 $(SECRET_SERVER_INTEGRATION_PACKAGES) -run '$(SECRET_SERVER_INTEGRATION_TESTS)'+PHONY_TARGETS += test\:apps\:secret-server\:secret-list-api+test\:apps\:secret-server\:secret-list-api: _ensure-apps-deps+ @bash apps/secret-server/tests/secret-list-api.sh+PHONY_TARGETS += test\:apps\:secret-server\:credential-apitest\:apps\:secret-server\:credential-api:@NODE_PATH="$${NODE_PATH:-$(PROJECT_ROOT)/apps/node_modules}" node apps/secret-server/tests/credential-api.cjsdiff --git a/openapi/box.openapi.yaml b/openapi/box.openapi.yamlindex 96782cc35..ae5fdf8e0 100644--- a/openapi/box.openapi.yaml+++ b/openapi/box.openapi.yaml@@ -316,6 +316,90 @@ paths:# -------------------------------------------------------------------------# Boxes# -------------------------------------------------------------------------+ /secrets:+ get:+ operationId: listOrganizationSecrets+ summary: List named secrets in the caller's organization+ description: Requires read:secrets. Results are ordered by immutable secret ID.+ parameters:+ - name: pageSize+ in: query+ description: Maximum number of organization secrets per page+ schema: { type: integer, minimum: 1, maximum: 100, default: 100 }+ - $ref: "#/components/parameters/pageToken"+ responses:+ "200":+ description: Organization secrets with their stored routing policy and placeholder+ content:+ application/json:+ schema:+ type: object+ required: [secrets]+ properties:+ secrets:+ type: array+ items:+ $ref: "#/components/schemas/OrganizationSecretListItem"+ next_page_token:+ type: string+ "400":+ $ref: "#/components/responses/BadRequestError"+ "403":+ description: Caller lacks permission to list organization secrets+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"+ post:+ operationId: createOrganizationSecret+ summary: Save a named secret for use by Boxes in the caller's organization+ description: Requires the hosted secret store and write:secrets permission.+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/SecretSpec"+ responses:+ "201":+ description: Secret created+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/OrganizationSecretIdentity"+ "400":+ $ref: "#/components/responses/BadRequestError"+ "403":+ description: Caller lacks permission to provision organization secrets+ "409":+ $ref: "#/components/responses/ConflictError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"++ /secrets/{secret_id}:+ delete:+ operationId: deleteOrganizationSecret+ summary: Delete an unused named secret by ID+ description: Requires write:secrets. A stopped Box retains its reference until destruction.+ parameters:+ - name: secret_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ responses:+ "204":+ description: Removal confirmed, including a repeated request by the owning organization+ "400":+ $ref: "#/components/responses/BadRequestError"+ "403":+ description: Caller lacks permission to delete organization secrets+ "404":+ description: No organization secret with this ID belongs to the caller's organization+ "409":+ description: A Box still references the secret+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"+/{prefix}/boxes:parameters:- $ref: "#/components/parameters/prefix"@@ -3658,9 +3742,13 @@ components:secrets:type: arrayitems:- $ref: "#/components/schemas/SecretSpec"+ oneOf:+ - $ref: "#/components/schemas/SecretSpec"+ - $ref: "#/components/schemas/OrganizationSecretReference"description: |Secrets injected into a request header on outbound HTTPS requests.+ Hosted requests may mix inline entries with organization secret references.+ Each reference uses the stored injection policy and is resolved at Box creation.Requests to a secret's hosts replace only configured headers alreadypresent in the request. A host that echoes theinjected header returns the value to the guest, so bind secrets only to@@ -4031,8 +4119,55 @@ components:layer enforces an inbound allowlist today, so inbound access iscontrolled by `mode` alone. Omit it, or send an empty array.+ OrganizationSecretReference:+ type: object+ additionalProperties: false+ required: [secret]+ properties:+ secret:+ type: string+ minLength: 1+ maxLength: 64+ description: Name of a secret in the authenticated caller's organization.++ OrganizationSecretIdentity:+ type: object+ required: [id, name]+ additionalProperties: false+ properties:+ id:+ type: string+ format: uuid+ name:+ type: string++ OrganizationSecretListItem:+ type: object+ required: [id, name, hosts, headers, placeholder]+ additionalProperties: false+ properties:+ id:+ type: string+ format: uuid+ name:+ type: string+ hosts:+ type: array+ items:+ type: string+ description: Stored list of hosts where the secret applies.+ headers:+ type: object+ additionalProperties:+ type: string+ description: Stored header templates with the literal {value} substitution marker.+ placeholder:+ type: string+ description: Stored guest placeholder, including any custom value supplied at creation.+SecretSpec:type: object+ additionalProperties: falsedescription: Secret injected into a request header on outbound HTTPS requests to its hostsrequired: [name, value, hosts, headers]properties:diff --git a/sdks/c/include/boxlite.h b/sdks/c/include/boxlite.hindex e4bdc5e37..e94ccb019 100644--- a/sdks/c/include/boxlite.h+++ b/sdks/c/include/boxlite.h@@ -1967,6 +1967,12 @@ void boxlite_options_add_secret_with_headers(CBoxliteOptions *opts,const char *const *header_templates,int headers_count);+// Add a hosted organization secret by name in request order.+// # Safety+// A non-null options pointer must reference a live, exclusively accessible handle.+// A non-null name must reference a readable NUL-terminated UTF-8 string.+enum BoxliteErrorCode boxlite_options_add_secret_reference(CBoxliteOptions *opts, const char *name);+// Deprecated: use `boxlite_options_set_auto_delete_interval`.void boxlite_options_set_auto_remove(CBoxliteOptions *opts, int val);diff --git a/sdks/c/src/checkpoints.rs b/sdks/c/src/checkpoints.rsindex deade9cbd..d052b9f52 100644--- a/sdks/c/src/checkpoints.rs+++ b/sdks/c/src/checkpoints.rs@@ -806,7 +806,7 @@ mod tests {);assert_eq!(drain(&mut runtime), (BoxliteErrorCode::Ok, "1".into()));let options = Box::into_raw(Box::new(crate::options::OptionsHandle {- options: boxlite::BoxOptions::default(),+ options: boxlite::BoxOptions::default().into(),name: None,checkpoint_override: false,checkpoint_selected: false,diff --git a/sdks/c/src/options.rs b/sdks/c/src/options.rsindex a535ab423..8e709445d 100644--- a/sdks/c/src/options.rs+++ b/sdks/c/src/options.rs@@ -9,7 +9,7 @@ use crate::util::c_str_to_string;use crate::{CBoxliteError, CBoxliteOptions};pub struct OptionsHandle {- pub options: BoxOptions,+ pub options: boxlite::CreateBoxOptions,pub name: Option<String>,pub(crate) checkpoint_override: bool,pub(crate) checkpoint_selected: bool,@@ -74,7 +74,8 @@ mod required_headers_tests {options: BoxOptions {rootfs: boxlite::RootfsSpec::RootfsPath(rootfs.to_string_lossy().into_owned()),..Default::default()- },+ }+ .into(),name: None,checkpoint_override: false,checkpoint_selected: false,@@ -365,6 +366,29 @@ pub unsafe extern "C" fn boxlite_options_add_secret_with_headers(}}+/// Add a hosted organization secret by name in request order.+/// # Safety+/// A non-null options pointer must reference a live, exclusively accessible handle.+/// A non-null name must reference a readable NUL-terminated UTF-8 string.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn boxlite_options_add_secret_reference(+ opts: *mut CBoxliteOptions,+ name: *const c_char,+) -> BoxliteErrorCode {+ let Some(opts) = (unsafe { opts.as_mut() }) else {+ return BoxliteErrorCode::InvalidArgument;+ };+ let Ok(name) = (unsafe { c_str_to_string(name) }) else {+ return BoxliteErrorCode::InvalidArgument;+ };+ if name.is_empty() {+ return BoxliteErrorCode::InvalidArgument;+ }+ opts.checkpoint_override = true;+ opts.options.secrets.push_reference(name);+ BoxliteErrorCode::Ok+}+/// Deprecated: use `boxlite_options_set_auto_delete_interval`.#[unsafe(no_mangle)]pub unsafe extern "C" fn boxlite_options_set_auto_remove(opts: *mut CBoxliteOptions, val: c_int) {@@ -508,7 +532,8 @@ pub unsafe fn options_new(options: BoxOptions {rootfs: RootfsSpec::Image(image_str),..Default::default()- },+ }+ .into(),name: None,checkpoint_override: false,checkpoint_selected: false,@@ -889,7 +914,7 @@ mod headers_map_tests {let empty = CString::new("").unwrap();for (template_ptr, expected) in [(template.as_ptr(), "Bot {value}"), (empty.as_ptr(), "")] {let mut handle = OptionsHandle {- options: BoxOptions::default(),+ options: BoxOptions::default().into(),name: None,checkpoint_override: false,checkpoint_selected: false,@@ -907,7 +932,11 @@ mod headers_map_tests {1,);}- let wire = serde_json::to_value(&handle.options.secrets[0]).unwrap();+ let options = BoxOptions::try_from(handle.options.clone()).unwrap();+ let [secret] = options.secrets.as_slice() else {+ panic!("expected one inline secret")+ };+ let wire = serde_json::to_value(secret).unwrap();assert_eq!(wire["headers"]["Authorization"], expected);}}diff --git a/sdks/c/src/tests.rs b/sdks/c/src/tests.rsindex 880fa24fc..ecbeba61b 100644--- a/sdks/c/src/tests.rs+++ b/sdks/c/src/tests.rs@@ -550,8 +550,8 @@ fn null_capability_element_cannot_weaken_policy() {BoxliteErrorCode::InvalidArgument);boxlite_options_set_advanced(opts, advanced);- (*opts)- .options+ boxlite::BoxOptions::try_from((*opts).options.clone())+ .expect("inline options must convert for local execution").sanitize().expect_err("a null cap_drop element must fail closed");boxlite_advanced_options_free(advanced);@@ -572,8 +572,8 @@ fn invalid_utf8_capability_cannot_weaken_policy() {BoxliteErrorCode::InvalidArgument);boxlite_options_set_advanced(opts, advanced);- (*opts)- .options+ boxlite::BoxOptions::try_from((*opts).options.clone())+ .expect("inline options must convert for local execution").sanitize().expect_err("invalid UTF-8 in cap_add must fail closed");boxlite_advanced_options_free(advanced);@@ -774,6 +774,58 @@ unsafe fn new_test_options() -> *mut CBoxliteOptions {opts}+#[test]+fn secret_reference_setter_rejects_missing_names_and_preserves_order() {+ use crate::options::{+ boxlite_options_add_secret_reference, boxlite_options_add_secret_with_headers,+ };++ unsafe {+ let mut opts = Box::from_raw(new_test_options());+ assert_eq!(+ boxlite_options_add_secret_reference(ptr::null_mut(), c"shared".as_ptr()),+ BoxliteErrorCode::InvalidArgument+ );+ for name in [ptr::null(), c"".as_ptr()] {+ assert_eq!(+ boxlite_options_add_secret_reference(&mut *opts, name),+ BoxliteErrorCode::InvalidArgument+ );+ }+ assert_eq!(+ serde_json::to_value(&opts.options.secrets).unwrap(),+ serde_json::json!([])+ );+ assert!(!opts.checkpoint_override);++ assert_eq!(+ boxlite_options_add_secret_reference(&mut *opts, c"first".as_ptr()),+ BoxliteErrorCode::Ok+ );+ assert!(opts.checkpoint_override);+ boxlite_options_add_secret_with_headers(+ &mut *opts,+ c"private".as_ptr(),+ c"value".as_ptr(),+ ptr::null(),+ [c"example.com".as_ptr()].as_ptr(),+ 1,+ [c"Authorization".as_ptr()].as_ptr(),+ [c"Bearer {value}".as_ptr()].as_ptr(),+ 1,+ );+ assert_eq!(+ boxlite_options_add_secret_reference(&mut *opts, c"last".as_ptr()),+ BoxliteErrorCode::Ok+ );+ let entries = serde_json::to_value(&opts.options.secrets).unwrap();+ assert_eq!(entries.as_array().unwrap().len(), 3);+ assert_eq!(entries[0], serde_json::json!({"secret": "first"}));+ assert_eq!(entries[1]["name"], "private");+ assert_eq!(entries[2], serde_json::json!({"secret": "last"}));+ }+}+unsafe fn new_test_advanced_options() -> *mut CAdvancedBoxOptions {let mut slot = MaybeUninit::<*mut CAdvancedBoxOptions>::uninit();let mut error = FFIError::default();diff --git a/sdks/go/options.go b/sdks/go/options.goindex b9eb0ddce..fe14a91ed 100644--- a/sdks/go/options.go+++ b/sdks/go/options.go@@ -9,6 +9,7 @@ import ("fmt""os""strings"+ "unicode/utf8""unsafe")@@ -234,6 +235,11 @@ type Secret struct {Headers map[string]string}+type createSecret struct {+ Secret+ named bool+}+type boxConfig struct {checkpointSet boolcheckpointOverride bool@@ -257,7 +263,7 @@ type boxConfig struct {detach *boolnetwork *NetworkSpecnetworkErr error // deferred WithNetwork validation error, surfaced at conversion- secrets []Secret+ secrets []createSecretadvanced *AdvancedBoxOptions // nil = runtime defaults; non-nil = caller-owned advanced opts applied via boxlite_options_set_advanced}@@ -455,7 +461,15 @@ func WithSecret(secret Secret) BoxOption {return func(c *boxConfig) {c.checkpointOverride = true- c.secrets = append(c.secrets, secret)+ c.secrets = append(c.secrets, createSecret{Secret: secret})+ }+}++// WithSecretReference adds an organization secret to a hosted Box.+func WithSecretReference(name string) BoxOption {+ return func(c *boxConfig) {+ c.checkpointOverride = true+ c.secrets = append(c.secrets, createSecret{Secret: Secret{Name: name}, named: true})}}@@ -548,6 +562,12 @@ func buildCOptions(image string, cfg *boxConfig) (*C.CBoxliteOptions, error) {}// C strings cannot carry NUL; reject it before conversion can hide it from Rust.for _, secret := range cfg.secrets {+ if secret.named {+ if secret.Name == "" || strings.ContainsRune(secret.Name, 0) || !utf8.ValidString(secret.Name) {+ return nil, &Error{Code: ErrInvalidArgument, Message: "invalid organization secret name"}+ }+ continue+ }if len(secret.Headers) == 0 {return nil, &Error{Code: ErrInvalidArgument, Message: fmt.Sprintf("secret %q has no headers; recreate the box with headers", secret.Name)}}@@ -711,6 +731,15 @@ func buildCOptions(image string, cfg *boxConfig) (*C.CBoxliteOptions, error) {}for _, secret := range cfg.secrets {cName := toCString(secret.Name)+ if secret.named {+ result := C.boxlite_options_add_secret_reference(cOpts, cName)+ C.free(unsafe.Pointer(cName))+ if result != C.Ok {+ C.boxlite_options_free(cOpts)+ return nil, &Error{Code: ErrInvalidArgument, Message: "invalid organization secret name"}+ }+ continue+ }cValue := toCString(secret.Value)placeholder := secret.Placeholderif placeholder == "" {diff --git a/sdks/go/required_headers_test.go b/sdks/go/required_headers_test.goindex 79f16031e..cfa9d4c19 100644--- a/sdks/go/required_headers_test.go+++ b/sdks/go/required_headers_test.go@@ -13,7 +13,8 @@ func TestRequiredHeadersBeforeCConversion(t *testing.T) {if err := json.Unmarshal([]byte(`{"Name":"x","Value":"token","Hosts":["api.test.com"]`+input+`}`), &secret); err != nil {t.Fatal(err)}- cfg := &boxConfig{secrets: []Secret{secret}}+ cfg := &boxConfig{}+ WithSecret(secret)(cfg)err := buildAndFreeCOptions("alpine", cfg)if !IsInvalidArgument(err) || !strings.Contains(err.Error(), `secret "x" has no headers; recreate the box with headers`) {t.Fatalf("expected actionable missing headers error, got %v", err)diff --git a/sdks/go/secret_headers_test.go b/sdks/go/secret_headers_test.goindex 6a1cc2cfe..e7a15b76b 100644--- a/sdks/go/secret_headers_test.go+++ b/sdks/go/secret_headers_test.go@@ -70,13 +70,56 @@ func TestSecretHeadersRestRequest(t *testing.T) {if got.Name != "test" || got.Value != "token" || !reflect.DeepEqual(got.Hosts, []string{"api.example.com"}) {t.Fatal("secret fields changed across REST boundary")}+ mixed, err := runtime.Create(ctx, "alpine", WithSecretReference("openai"), WithSecret(secret))+ if err != nil {+ t.Fatal(err)+ }+ defer mixed.Close()+ var entries []map[string]any+ if err := json.Unmarshal((<-requests)["secrets"], &entries); err != nil {+ t.Fatal(err)+ }+ if len(entries) != 2 || !reflect.DeepEqual(entries[0], map[string]any{"secret": "openai"}) || entries[1]["value"] != secret.Value {+ t.Fatal("mixed secret references or ordering changed")+ }if !reflect.DeepEqual(got.Headers, tc.want) {t.Fatalf("REST headers = %v, want %v", got.Headers, tc.want)}+ boxWithRef, created, err := runtime.GetOrCreate(ctx, "alpine", WithSecretReference("shared"))+ if err != nil {+ t.Fatal(err)+ }+ defer boxWithRef.Close()+ var refs []map[string]string+ if err := json.Unmarshal((<-requests)["secrets"], &refs); err != nil {+ t.Fatal(err)+ }+ if !created || !reflect.DeepEqual(refs, []map[string]string{{"secret": "shared"}}) {+ t.Fatalf("GetOrCreate: created=%t refs=%v", created, refs)+ }})}}+func TestSecretReferenceRejectsInvalidNameBeforeSending(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Errorf("invalid reference reached %s %s", r.Method, r.URL.Path)+ w.WriteHeader(http.StatusBadRequest)+ }))+ defer server.Close()+ runtime, err := NewRest(BoxliteRestOptions{URL: server.URL})+ if err != nil {+ t.Fatal(err)+ }+ defer runtime.Close()+ for _, name := range []string{"", "shared\x00suffix", "\xff"} {+ _, err := runtime.Create(context.Background(), "alpine", WithSecretReference(name))+ if !IsInvalidArgument(err) || !strings.Contains(err.Error(), "invalid organization secret name") {+ t.Errorf("Create with name %q: got %v", name, err)+ }+ }+}+func TestSecretHeadersRejectedBeforeRootfsSetup(t *testing.T) {runtime := newTestRuntime(t)var secret Secretdiff --git a/sdks/node/Cargo.toml b/sdks/node/Cargo.tomlindex 314aabdb4..0d20071ba 100644--- a/sdks/node/Cargo.toml+++ b/sdks/node/Cargo.toml@@ -18,6 +18,7 @@ boxlite-shared.workspace = true# napi-rs for Node.js bindingsnapi = { version = "3.16.1", features = ["async", "napi8", "tokio_rt", "serde-json"] }napi-derive = "3.7.0"+serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"# Async runtimediff --git a/sdks/node/lib/native-contracts.ts b/sdks/node/lib/native-contracts.tsindex 88caa0667..c954bb9ec 100644--- a/sdks/node/lib/native-contracts.ts+++ b/sdks/node/lib/native-contracts.ts@@ -377,7 +377,7 @@ export interface JsBoxOptions {advanced?: JsAdvancedBoxOptions;security?: JsSecurityOptions;healthCheck?: JsHealthCheckOptions;- secrets?: JsSecret[];+ secrets?: (JsSecret | { secret: string })[];}export interface JsOptions {diff --git a/sdks/node/lib/simplebox.ts b/sdks/node/lib/simplebox.tsindex 51c41fabd..ee7eb4103 100644--- a/sdks/node/lib/simplebox.ts+++ b/sdks/node/lib/simplebox.ts@@ -340,7 +340,7 @@ export interface SimpleBoxOptions {network?: NetworkSpec;/** Secrets to inject into outbound HTTPS requests. */- secrets?: Secret[];+ secrets?: (Secret | { secret: string })[];/*** Override image ENTRYPOINT directive.diff --git a/sdks/node/lib/skillbox.ts b/sdks/node/lib/skillbox.tsindex c245fb0aa..e87a50eae 100644--- a/sdks/node/lib/skillbox.ts+++ b/sdks/node/lib/skillbox.ts@@ -73,7 +73,7 @@ export interface SkillBoxOptions {/** Structured network configuration. */network?: NetworkSpec;/** Secrets to inject into outbound HTTPS requests. */- secrets?: Secret[];+ secrets?: (Secret | { secret: string })[];/** Optional runtime instance */runtime?: JsBoxlite;}diff --git a/sdks/node/src/options.rs b/sdks/node/src/options.rsindex 510714903..c78a01a77 100644--- a/sdks/node/src/options.rs+++ b/sdks/node/src/options.rs@@ -6,9 +6,9 @@ use boxlite::runtime::advanced_options::{};use boxlite::runtime::constants::images;use boxlite::runtime::options::{- BoxOptions, BoxliteOptions, ImageRegistry, ImageRegistryAuth, InboundNetworkConfig,- NetworkMode, NetworkSpec, OutboundNetworkConfig, PortProtocol, PortSpec, RegistryTransport,- RootfsSpec, Secret, VolumeSpec,+ BoxOptions, BoxliteOptions, CreateBoxOptions, ImageRegistry, ImageRegistryAuth,+ InboundNetworkConfig, NetworkMode, NetworkSpec, OutboundNetworkConfig, PortProtocol, PortSpec,+ RegistryTransport, RootfsSpec, Secret, VolumeSpec,};use napi::bindgen_prelude::Error;use napi_derive::napi;@@ -253,7 +253,8 @@ pub struct JsBoxOptions {pub health_check: Option<JsHealthCheckOptions>,/// Secrets to inject into outbound HTTPS requests via MITM proxy.- pub secrets: Option<Vec<JsSecret>>,+ #[napi(ts_type = "Array<JsSecret | { secret: string }>")]+ pub secrets: Option<Vec<serde_json::Value>>,}/// Environment variable specification.@@ -337,7 +338,7 @@ pub struct JsPortSpec {/// Secret injection configuration.#[napi(object)]-#[derive(Clone, Debug)]+#[derive(Clone, Debug, serde::Deserialize)]pub struct JsSecret {/// Human-readable name for the secret.pub name: String,@@ -493,7 +494,7 @@ impl TryFrom<JsNetworkSpec> for (NetworkSpec, NetworkSpec) {}}-impl TryFrom<JsBoxOptions> for BoxOptions {+impl TryFrom<JsBoxOptions> for CreateBoxOptions {type Error = boxlite_shared::errors::BoxliteError;/// Reject supplied checkpoint settings before conversion erases defaults.@@ -598,32 +599,41 @@ impl TryFrom<JsBoxOptions> for BoxOptions {.advanced.and_then(|advanced| advanced.capabilities).map(Into::into);- let secrets = js_opts- .secrets- .unwrap_or_default()- .into_iter()- .map(|secret| {- // Deserialize the map shape explicitly: N-API's HashMap conversion- // also accepts arrays as numeric header names.- let headers = serde_json::from_value::<std::collections::BTreeMap<String, String>>(- secret.headers,+ let mut secrets = boxlite::runtime::options::SecretBindings::default();+ for entry in js_opts.secrets.unwrap_or_default() {+ if let Some(name) = entry.get("secret") {+ if let Some(name) = name.as_str()+ && entry.as_object().is_some_and(|o| o.len() == 1)+ {+ secrets.push_reference(name);+ continue;+ }+ return Err(Self::Error::InvalidArgument(+ "a named secret takes only a string secret key".into(),+ ));+ }+ let secret: JsSecret = serde_json::from_value(entry)+ .map_err(|_| Self::Error::InvalidArgument("invalid inline secret".into()))?;+ // Deserialize the map shape explicitly: N-API's HashMap conversion+ // also accepts arrays as numeric header names.+ let headers = serde_json::from_value::<std::collections::BTreeMap<String, String>>(+ secret.headers,+ )+ .map_err(|_| {+ Self::Error::InvalidArgument(+ "Secret.headers must map header names to string templates".into(),)- .map_err(|_| {- Self::Error::InvalidArgument(- "Secret.headers must map header names to string templates".into(),- )- })?;- Ok(Secret {- placeholder: secret- .placeholder- .unwrap_or_else(|| format!("<BOXLITE_SECRET:{}>", secret.name)),- name: secret.name,- value: secret.value,- hosts: secret.hosts.unwrap_or_default(),- headers: Some(headers),- })- })- .collect::<Result<Vec<_>, Self::Error>>()?;+ })?;+ secrets.push(Secret {+ placeholder: secret+ .placeholder+ .unwrap_or_else(|| format!("<BOXLITE_SECRET:{}>", secret.name)),+ name: secret.name,+ value: secret.value,+ hosts: secret.hosts.unwrap_or_default(),+ headers: Some(headers),+ });+ }let mut advanced = AdvancedBoxOptions::default();advanced.set_privileged(privileged);@@ -631,7 +641,7 @@ impl TryFrom<JsBoxOptions> for BoxOptions {advanced.security = security;advanced.health_check = health_check;- Ok(BoxOptions {+ Ok(CreateBoxOptions {cpus: js_opts.cpus,memory_mib: js_opts.memory_mib,disk_size_gb: js_opts.disk_size_gb.map(|v| v as u64),@@ -1009,18 +1019,21 @@ mod tests {for cores in [0.125, 0.126, 1.5, 2.0] {let mut options = js.clone();options.cpus = Some(cores);- assert_eq!(BoxOptions::try_from(options).unwrap().cpus, Some(cores));+ assert_eq!(+ CreateBoxOptions::try_from(options).unwrap().cpus,+ Some(cores)+ );}for cores in [0.0, -0.5, 0.124, 0.1255, f64::NAN, f64::INFINITY] {let mut options = js.clone();options.cpus = Some(cores);- assert!(BoxOptions::try_from(options).is_err(), "{cores}");+ assert!(CreateBoxOptions::try_from(options).is_err(), "{cores}");}let mut both = js.clone();both.auto_remove = Some(false);both.auto_delete = Some(60);- let both = BoxOptions::try_from(both).unwrap();+ let both = CreateBoxOptions::try_from(both).unwrap();assert!(!both.auto_remove);assert_eq!(both.auto_delete, Some(60));@@ -1032,7 +1045,7 @@ mod tests {drop: Some(vec!["MKNOD".into(), "NET_RAW".into()]),}),});- let with_capabilities = BoxOptions::try_from(with_capabilities).unwrap();+ let with_capabilities = CreateBoxOptions::try_from(with_capabilities).unwrap();let capabilities = with_capabilities.advanced.capabilities()@@ -1045,12 +1058,12 @@ mod tests {privileged: Some(true),capabilities: None,});- let privileged = BoxOptions::try_from(privileged).unwrap();+ let privileged = CreateBoxOptions::try_from(privileged).unwrap();assert!(privileged.advanced.privileged);assert_eq!(privileged.advanced.security, SecurityOptions::default());assert!(privileged.advanced.capabilities().is_none());- let opts = BoxOptions::try_from(js).unwrap();+ let opts = CreateBoxOptions::try_from(js).unwrap();assert!(!opts.auto_remove);assert_eq!(opts.auto_delete, None);assert!(opts.advanced.capabilities().is_none());@@ -1066,9 +1079,8 @@ mod tests {}}- #[test]- fn secret_headers_binding_preserves_templates() {- let js = JsBoxOptions {+ fn js_options_with_secrets(secrets: Vec<serde_json::Value>) -> JsBoxOptions {+ JsBoxOptions {image: Some("python:slim".into()),rootfs_path: None,checkpoint: None,@@ -1091,25 +1103,61 @@ mod tests {advanced: None,security: None,health_check: None,- secrets: Some(vec![JsSecret {- name: "openai".into(),- value: "sk-test".into(),- hosts: Some(vec!["api.openai.com".into()]),- placeholder: None,- headers: serde_json::json!({"Authorization": "Bot {value}", "X-Key": "{value}"}),- }]),- };+ secrets: Some(secrets),+ }+ }- let opts = BoxOptions::try_from(js).unwrap();- assert_eq!(opts.secrets.len(), 1);- assert_eq!(opts.secrets[0].name, "openai");- assert_eq!(opts.secrets[0].hosts, vec!["api.openai.com"]);- assert_eq!(opts.secrets[0].placeholder, "<BOXLITE_SECRET:openai>");- let wire = serde_json::to_value(&opts.secrets[0]).unwrap();+ #[test]+ fn secret_headers_binding_preserves_templates() {+ let js = js_options_with_secrets(vec![serde_json::json!({+ "name": "openai", "value":"sk-test","hosts":["api.openai.com"],+ "headers":{"Authorization":"Bot {value}","X-Key":"{value}"}+ })]);+ let options = BoxOptions::try_from(CreateBoxOptions::try_from(js).unwrap()).unwrap();+ let [secret] = options.secrets.as_slice() else {+ panic!("expected one inline secret")+ };+ assert_eq!(secret.name, "openai");+ assert_eq!(secret.hosts, vec!["api.openai.com"]);+ assert_eq!(secret.placeholder, "<BOXLITE_SECRET:openai>");+ let wire = serde_json::to_value(secret).unwrap();assert_eq!(wire["headers"]["Authorization"], "Bot {value}");assert_eq!(wire["headers"]["X-Key"], "{value}");}+ #[test]+ fn secret_binding_accepts_a_name_without_inline_fields() {+ let js = js_options_with_secrets(vec![serde_json::json!({"secret": "shared"})]);+ let entries = CreateBoxOptions::try_from(js).unwrap().secrets;+ assert_eq!(+ serde_json::to_value(entries).unwrap(),+ serde_json::json!([{"secret": "shared"}])+ );+ }++ #[test]+ fn secret_binding_rejects_ambiguous_and_malformed_entries() {+ for (entry, expected) in [+ (+ serde_json::json!({"secret": 42}),+ "a named secret takes only a string secret key",+ ),+ (+ serde_json::json!({"secret": "shared", "value": "override"}),+ "a named secret takes only a string secret key",+ ),+ (+ serde_json::json!({"name": "inline"}),+ "invalid inline secret",+ ),+ ] {+ let result = CreateBoxOptions::try_from(js_options_with_secrets(vec![entry]));+ assert!(+ matches!(result, Err(boxlite::BoxliteError::InvalidArgument(message)) if message == expected)+ );+ }+ }+#[test]fn disabled_network_rejects_allow_net() {let err = <(NetworkSpec, NetworkSpec)>::try_from(JsNetworkSpec {diff --git a/sdks/node/src/runtime.rs b/sdks/node/src/runtime.rsindex f458dd08f..358c31e36 100644--- a/sdks/node/src/runtime.rs+++ b/sdks/node/src/runtime.rs@@ -1,7 +1,7 @@use std::sync::Arc;use boxlite::experimental::{ExperimentalFeatures, RuntimeBuilder};-use boxlite::{BoxArchive, BoxOptions, BoxliteOptions, BoxliteRuntime};+use boxlite::{BoxArchive, BoxliteOptions, BoxliteRuntime};use napi::bindgen_prelude::*;use napi_derive::napi;@@ -141,7 +141,7 @@ impl JsBoxlite {#[napi]pub async fn create(&self, options: JsBoxOptions, name: Option<String>) -> Result<JsBox> {let runtime = Arc::clone(&self.runtime);- let options = BoxOptions::try_from(options).map_err(map_err)?;+ let options = boxlite::CreateBoxOptions::try_from(options).map_err(map_err)?;let handle = runtime.create(options, name).await.map_err(map_err)?;Ok(JsBox {@@ -175,7 +175,7 @@ impl JsBoxlite {name: Option<String>,) -> Result<JsGetOrCreateResult> {let runtime = Arc::clone(&self.runtime);- let options = BoxOptions::try_from(options).map_err(map_err)?;+ let options = boxlite::CreateBoxOptions::try_from(options).map_err(map_err)?;let (handle, created) = runtime.get_or_create(options, name).awaitdiff --git a/sdks/node/tests/options/checkpoint_options.rs b/sdks/node/tests/options/checkpoint_options.rsindex b11d2b5ca..e021e0f66 100644--- a/sdks/node/tests/options/checkpoint_options.rs+++ b/sdks/node/tests/options/checkpoint_options.rs@@ -30,7 +30,7 @@ fn checkpoint_options() -> JsBoxOptions {#[test]fn checkpoint_conversion_rejects_explicit_defaults_and_empty_collections() {- let plain = BoxOptions::try_from(checkpoint_options()).unwrap();+ let plain = CreateBoxOptions::try_from(checkpoint_options()).unwrap();assert!(matches!(plain.rootfs, RootfsSpec::Checkpoint(_)));let mutations: &[fn(&mut JsBoxOptions)] = &[|o| o.auto_remove = Some(true),@@ -61,7 +61,7 @@ fn checkpoint_conversion_rejects_explicit_defaults_and_empty_collections() {let mut options = checkpoint_options();mutate(&mut options);if !matches!(- BoxOptions::try_from(options),+ CreateBoxOptions::try_from(options),Err(boxlite::BoxliteError::InvalidArgument(_))) {ignored.push(index);diff --git a/sdks/node/tests/secret-headers.test.ts b/sdks/node/tests/secret-headers.test.tsindex 2a564f612..658e8803a 100644--- a/sdks/node/tests/secret-headers.test.ts+++ b/sdks/node/tests/secret-headers.test.ts@@ -67,6 +67,26 @@ describe.skipIf(!nativeBuilt)("secret headers native boundary", () => {delete requests[0].secrets[0].headers;delete requests[1].secrets[0].headers;expect(requests[1]).toEqual(requests[0]);+ const ref = { secret: "openai" };+ const inline = {+ name: "bot",+ value: "token",+ hosts: ["api.example.com"],+ headers: templates,+ };+ await runtime.create({ image: "alpine:latest", secrets: [ref, inline] });+ expect(requests.at(-1)?.secrets).toEqual([+ ref,+ { ...inline, placeholder: "<BOXLITE_SECRET:bot>" },+ ]);+ await runtime.create({ image: "alpine:latest", secrets: [ref] });+ expect(requests.at(-1)?.secrets).toEqual([ref]);+ await expect(+ runtime.create({+ image: "alpine:latest",+ secrets: [{ ...ref, ...inline }],+ }),+ ).rejects.toThrow(/only/);} finally {runtime.close();server.closeAllConnections();diff --git a/sdks/python/README.md b/sdks/python/README.mdindex d323fefce..b31c48ed4 100644--- a/sdks/python/README.md+++ b/sdks/python/README.md@@ -371,7 +371,7 @@ Configuration options for creating a box.pass `False` for a private cloud tunnel. Call `forward()` for a listener;connections reuse the declaration and cannot undo revocation. See[private tunnel examples](../../docs/concepts/networking.md#private-cloud-tunnels).-- `secrets: List[Secret]` - Secrets overwrite configured headers already present on outbound HTTPS requests.+- `secrets` - Pass inline `Secret` objects to overwrite configured headers on outbound HTTPS requests. With a hosted runtime, include `{"secret": "openai"}` to use an organization secret by name.`Secret(..., headers={"x-goog-api-key": "{value}"})` selects a raw API key header;multiple entries share the same secret value. Each template must contain exactly one `{value}`.`headers` is a required keyword argument; omission, `None`, empty maps and strings are rejected.diff --git a/sdks/python/src/options.rs b/sdks/python/src/options.rsindex 2f6a896a4..126ebcd18 100644--- a/sdks/python/src/options.rs+++ b/sdks/python/src/options.rs@@ -5,9 +5,9 @@ use boxlite::litebox::copy::CopyOptions;use boxlite::runtime::advanced_options::{HealthCheckOptions, SecurityOptions};use boxlite::runtime::constants::images;use boxlite::runtime::options::{- BoxOptions, BoxliteOptions, ImageRegistry, ImageRegistryAuth, InboundNetworkConfig,- NetworkMode, NetworkSpec, OutboundNetworkConfig, PortProtocol, PortSpec, RegistryTransport,- RootfsSpec, VolumeSpec,+ BoxOptions, BoxliteOptions, CreateBoxOptions, ImageRegistry, ImageRegistryAuth,+ InboundNetworkConfig, NetworkMode, NetworkSpec, OutboundNetworkConfig, PortProtocol, PortSpec,+ RegistryTransport, RootfsSpec, VolumeSpec,};use pyo3::exceptions::{PyRuntimeError, PyValueError};use pyo3::prelude::*;@@ -537,6 +537,29 @@ impl PySecret {}}+#[derive(Clone, Debug)]+pub(crate) enum PyCreateSecret {+ Inline(PySecret),+ Named(String),+}++impl<'a, 'py> FromPyObject<'a, 'py> for PyCreateSecret {+ type Error = PyErr;+ fn extract(obj: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {+ if let Ok(dict) = obj.cast::<PyDict>() {+ if dict.len() == 1+ && let Some(name) = dict.get_item("secret")?+ {+ return Ok(Self::Named(name.extract()?));+ }+ return Err(PyValueError::new_err(+ "a named secret takes only the secret key",+ ));+ }+ Ok(Self::Inline(obj.extract()?))+ }+}+// ============================================================================// Box Options// ============================================================================@@ -603,8 +626,7 @@ pub(crate) struct PyBoxOptions {pub(crate) advanced: Option<PyAdvancedBoxOptions>,/// Secrets to inject into outbound HTTPS requests via MITM proxy.- #[pyo3(get)]- pub(crate) secrets: Vec<PySecret>,+ pub(crate) secrets: Vec<PyCreateSecret>,collection_options_supplied: bool,}@@ -658,7 +680,7 @@ impl PyBoxOptions {user: Option<String>,tty: Option<bool>,advanced: Option<PyAdvancedBoxOptions>,- secrets: Option<Vec<PySecret>>,+ secrets: Option<Vec<PyCreateSecret>>,checkpoint: Option<String>,) -> Self {let collection_options_supplied =@@ -697,9 +719,24 @@ impl PyBoxOptions {self.env = env;}+ #[getter(secrets)]+ fn get_secrets(&self, py: Python<'_>) -> PyResult<Vec<Py<PyAny>>> {+ self.secrets+ .iter()+ .map(|entry| match entry {+ PyCreateSecret::Inline(secret) => Ok(Py::new(py, secret.clone())?.into_any()),+ PyCreateSecret::Named(name) => {+ let reference = PyDict::new(py);+ reference.set_item("secret", name)?;+ Ok(reference.into_any().unbind())+ }+ })+ .collect()+ }+/// A supplied empty secret list must not silently inherit checkpoint secrets.#[setter]- fn set_secrets(&mut self, secrets: Vec<PySecret>) {+ fn set_secrets(&mut self, secrets: Vec<PyCreateSecret>) {self.collection_options_supplied = true;self.secrets = secrets;}@@ -716,7 +753,7 @@ impl PyBoxOptions {}}-impl TryFrom<PyBoxOptions> for BoxOptions {+impl TryFrom<PyBoxOptions> for CreateBoxOptions {type Error = boxlite::BoxliteError;/// Validate optional input presence before applying the core defaults.@@ -826,22 +863,22 @@ impl TryFrom<PyBoxOptions> for BoxOptions {}}- // Convert Python secrets to Rust secrets- opts.secrets = py_opts- .secrets- .into_iter()- .map(|s| boxlite::runtime::options::Secret {- name: s.name.clone(),- hosts: s.hosts,- placeholder: s- .placeholder- .unwrap_or_else(|| format!("<BOXLITE_SECRET:{}>", s.name)),- value: s.value,- headers: s.headers,- })- .collect();-- Ok(opts)+ let mut options = Self::from(opts);+ for entry in py_opts.secrets {+ match entry {+ PyCreateSecret::Named(name) => options.secrets.push_reference(name),+ PyCreateSecret::Inline(s) => options.secrets.push(boxlite::Secret {+ placeholder: s+ .placeholder+ .unwrap_or_else(|| format!("<BOXLITE_SECRET:{}>", s.name)),+ name: s.name,+ hosts: s.hosts,+ value: s.value,+ headers: s.headers,+ }),+ }+ }+ Ok(options)}}@@ -1338,7 +1375,7 @@ mod tests {#[test]fn secret_headers_binding_preserves_templates() {let mut options = py_box_options_with_tty(None);- options.secrets = vec![+ options.secrets = vec![PyCreateSecret::Inline(PySecret::new("bot".into(),"token".into(),@@ -1350,9 +1387,12 @@ mod tests {]),).unwrap(),- ];- let core = BoxOptions::try_from(options).unwrap();- let wire = serde_json::to_value(&core.secrets[0]).unwrap();+ )];+ let options = BoxOptions::try_from(CreateBoxOptions::try_from(options).unwrap()).unwrap();+ let [secret] = options.secrets.as_slice() else {+ panic!("inline expected")+ };+ let wire = serde_json::to_value(secret).unwrap();assert_eq!(wire["headers"]["Authorization"], "Bot {value}");assert_eq!(wire["headers"]["X-Key"], "{value}");}@@ -1373,7 +1413,7 @@ mod tests {capabilities: None,};- let opts = BoxOptions::try_from(py_box_options_with_advanced(advanced))+ let opts = CreateBoxOptions::try_from(py_box_options_with_advanced(advanced)).expect("security-only options should convert");assert!(@@ -1397,7 +1437,7 @@ mod tests {}),};- let opts = BoxOptions::try_from(py_box_options_with_advanced(advanced))+ let opts = CreateBoxOptions::try_from(py_box_options_with_advanced(advanced)).expect("explicit capabilities should convert");let capabilities = opts@@ -1415,7 +1455,7 @@ mod tests {health_check: None,capabilities: None,};- let opts = BoxOptions::try_from(py_box_options_with_advanced(advanced)).unwrap();+ let opts = CreateBoxOptions::try_from(py_box_options_with_advanced(advanced)).unwrap();assert!(opts.advanced.privileged);assert!(opts.advanced.capabilities().is_none());assert_eq!(opts.advanced.security, SecurityOptions::default());@@ -1538,7 +1578,7 @@ mod tests {/// terminal — the same class of silent drop this whole change closes.#[test]fn explicit_tty_reaches_core_box_options() {- let opts = BoxOptions::try_from(py_box_options_with_tty(Some(true)))+ let opts = CreateBoxOptions::try_from(py_box_options_with_tty(Some(true))).expect("tty=True should convert");assert!(opts.tty, "expected tty to reach core BoxOptions");@@ -1548,8 +1588,8 @@ mod tests {/// than writing `false` over whatever the core decides.#[test]fn unset_tty_preserves_the_core_default() {- let opts =- BoxOptions::try_from(py_box_options_with_tty(None)).expect("tty=None should convert");+ let opts = CreateBoxOptions::try_from(py_box_options_with_tty(None))+ .expect("tty=None should convert");assert_eq!(opts.tty,@@ -1562,13 +1602,13 @@ mod tests {for cores in [0.125, 0.126, 1.5, 2.0] {let mut options = py_box_options_with_tty(None);options.cpus = Some(cores);- let core = BoxOptions::try_from(options).unwrap();+ let core = CreateBoxOptions::try_from(options).unwrap();assert_eq!(core.cpus, Some(cores));}for cores in [0.0, -0.5, 0.124, 0.1255, f64::NAN, f64::INFINITY] {let mut options = py_box_options_with_tty(None);options.cpus = Some(cores);- assert!(BoxOptions::try_from(options).is_err(), "{cores}");+ assert!(CreateBoxOptions::try_from(options).is_err(), "{cores}");}}}diff --git a/sdks/python/src/runtime.rs b/sdks/python/src/runtime.rsindex 83f9c274b..f477349b1 100644--- a/sdks/python/src/runtime.rs+++ b/sdks/python/src/runtime.rs@@ -1,7 +1,7 @@use std::sync::Arc;use boxlite::experimental::{ExperimentalFeatures, RuntimeBuilder};-use boxlite::{BoxArchive, BoxOptions, BoxliteOptions, BoxliteRuntime};+use boxlite::{BoxArchive, BoxliteOptions, BoxliteRuntime};use pyo3::prelude::*;use crate::box_handle::PyBox;@@ -84,7 +84,7 @@ impl PyBoxlite {name: Option<String>,) -> PyResult<Bound<'py, PyAny>> {let runtime = Arc::clone(&self.runtime);- let opts = BoxOptions::try_from(options).map_err(map_err)?;+ let opts = boxlite::CreateBoxOptions::try_from(options).map_err(map_err)?;pyo3_async_runtimes::tokio::future_into_py(py, async move {let handle = runtime.create(opts, name).await.map_err(map_err)?;Ok(PyBox {@@ -149,7 +149,7 @@ impl PyBoxlite {name: Option<String>,) -> PyResult<Bound<'py, PyAny>> {let runtime = Arc::clone(&self.runtime);- let opts = BoxOptions::try_from(options).map_err(map_err)?;+ let opts = boxlite::CreateBoxOptions::try_from(options).map_err(map_err)?;pyo3_async_runtimes::tokio::future_into_py(py, async move {let (handle, created) = runtime.get_or_create(opts, name).await.map_err(map_err)?;Ok((diff --git a/sdks/python/tests/test_secret_headers_rest.py b/sdks/python/tests/test_secret_headers_rest.pyindex 09d5558c7..40bdb06b0 100644--- a/sdks/python/tests/test_secret_headers_rest.py+++ b/sdks/python/tests/test_secret_headers_rest.py@@ -25,39 +25,49 @@ def secret_with_headers(headers=_UNSET):return boxlite.Secret(**kwargs)-async def test_secret_headers_rest_request():+def secret_rest_server():requests = []- metadata = []+ boxes = {}class Handler(BaseHTTPRequestHandler):- def do_POST(self):- metadata.append((self.command, self.path, self.headers.get("Content-Type")))- requests.append(- (- self.path,- json.loads(self.rfile.read(int(self.headers["Content-Length"]))),- )- )- payload = json.dumps(- {- "box_id": "secret-test",- "name": None,- "status": "configured",- "created_at": "2026-01-01T00:00:00Z",- "updated_at": "2026-01-01T00:00:00Z",- "pid": None,- "image": "alpine:latest",- "cpus": 1,- "memory_mib": 512,- }- ).encode()- self.send_response(200)+ def reply(self, status, body):+ payload = json.dumps(body).encode()+ self.send_response(status)self.send_header("Content-Type", "application/json")self.send_header("Content-Length", str(len(payload)))self.end_headers()self.wfile.write(payload)+ def do_GET(self):+ requests.append((self.command, self.path, None))+ if self.path in boxes:+ self.reply(200, boxes[self.path])+ else:+ self.reply(404, {"message": "box not found"})++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ requests.append((self.command, self.path, body))+ if self.headers.get("Content-Type") != "application/json":+ self.reply(415, {"message": "expected JSON"})+ return+ info = {+ "box_id": "secret-test",+ "name": body.get("name"),+ "status": "configured",+ "created_at": "2026-01-01T00:00:00Z",+ "updated_at": "2026-01-01T00:00:00Z",+ "pid": None,+ "image": "alpine:latest",+ "cpus": 1,+ "memory_mib": 512,+ "privileged": False,+ }+ if info["name"]:+ boxes[f"/v1/boxes/{info['name']}"] = info+ self.reply(201, info)+def log_message(self, *args):pass@@ -67,22 +77,8 @@ async def test_secret_headers_rest_request():runtime = boxlite.Boxlite.rest(boxlite.BoxliteRestOptions(url=f"http://127.0.0.1:{server.server_port}"))- templates = {"Authorization": "Bot {value}", "X-Key": "{value}"}try:- for headers in [{"Authorization": "Bearer {value}"}, templates]:- await runtime.create(- boxlite.BoxOptions(- image="alpine:latest", secrets=[secret_with_headers(headers)]- )- )- assert [path for path, _ in requests] == ["/v1/boxes"] * 2- assert metadata == [("POST", "/v1/boxes", "application/json")] * 2- before, after = [body for _, body in requests]- assert before["secrets"][0].pop("headers") == {- "Authorization": "Bearer {value}"- }- assert after["secrets"][0].pop("headers", None) == templates- assert before == after+ yield runtime, requestsfinally:runtime.close()server.shutdown()@@ -90,6 +86,102 @@ async def test_secret_headers_rest_request():thread.join()+async def test_secret_headers_rest_request(secret_rest_server):+ runtime, requests = secret_rest_server+ templates = {"Authorization": "Bot {value}", "X-Key": "{value}"}+ for headers in [{"Authorization": "Bearer {value}"}, templates]:+ await runtime.create(+ boxlite.BoxOptions(+ image="alpine:latest", secrets=[secret_with_headers(headers)]+ )+ )+ assert [(method, path) for method, path, _ in requests] == [+ ("POST", "/v1/boxes")+ ] * 2+ before, after = [body for _, _, body in requests]+ assert before["secrets"][0].pop("headers") == {"Authorization": "Bearer {value}"}+ assert after["secrets"][0].pop("headers", None) == templates+ assert before == after++ await runtime.create(boxlite.BoxOptions(image="alpine:latest"))+ assert "secrets" not in requests[-1][2]++ ref = {"secret": "openai"}+ mixed = boxlite.BoxOptions(+ image="alpine:latest", secrets=[ref, secret_with_headers(templates)]+ )+ assert mixed.secrets[0] == ref+ await runtime.create(mixed)+ assert requests[-1][2]["secrets"] == [+ ref,+ {**after["secrets"][0], "headers": templates},+ ]++ await runtime.create(boxlite.BoxOptions(image="alpine:latest", secrets=[ref]))+ assert requests[-1][2]["secrets"] == [ref]+ with pytest.raises(ValueError, match="only"):+ boxlite.BoxOptions(secrets=[{"secret": "openai", "value": "override"}])+++async def test_get_or_create_named_secret_checks_existing_box(secret_rest_server):+ runtime, requests = secret_rest_server+ options = boxlite.BoxOptions(image="alpine:latest")+ options.secrets = [{"secret": "shared"}]+ box, created = await runtime.get_or_create(options, name="worker")+ assert created and box.id == "secret-test"+ assert len(requests) == 2+ assert requests[0] == ("GET", "/v1/boxes/worker", None)+ method, path, body = requests[1]+ assert (method, path, body["name"], body["secrets"]) == (+ "POST",+ "/v1/boxes",+ "worker",+ [{"secret": "shared"}],+ )+ requests.clear()++ with pytest.raises(+ boxlite.errors.UnsupportedError, match="cannot verify named secret bindings"+ ):+ await runtime.get_or_create(options, name="worker")+ assert requests == [("GET", "/v1/boxes/worker", None)]++ options.secrets = []+ box, created = await runtime.get_or_create(options, name="worker")+ assert not created and box.id == "secret-test"+ assert requests == [("GET", "/v1/boxes/worker", None)] * 2+++async def test_mixed_secrets_share_the_64_entry_limit(secret_rest_server):+ runtime, requests = secret_rest_server+ refs = [{"secret": f"shared_{i}"} for i in range(63)]+ inline = secret_with_headers({"Authorization": "Bearer {value}"})+ options = boxlite.BoxOptions(image="alpine:latest", secrets=[inline, *refs])+ await runtime.create(options)+ assert len(requests) == 1+ sent = requests[0][2]["secrets"]+ assert sent[0]["name"] == "bot" and sent[1:] == refs++ options.secrets = [inline, *refs, {"secret": "one_too_many"}]+ with pytest.raises(boxlite.errors.InvalidArgumentError, match="at most 64"):+ await runtime.create(options)+ assert len(requests) == 1+++ "bad, error",+ [({"secret": 42}, TypeError), ({"wrong": "key"}, ValueError), (None, TypeError)],+)+def test_secret_assignment_rejects_invalid_entries_atomically(bad, error):+ options = boxlite.BoxOptions(secrets=[{"secret": "original"}])+ with pytest.raises(error):+ options.secrets = [{"secret": "replacement"}, bad]+ assert options.secrets == [{"secret": "original"}]++@pytest.mark.asyncio@pytest.mark.parametrize("headers", [_UNSET, None, {}, "", {"Bad Header": "{value}"}])async def test_secret_headers_reject_invalid_input(tmp_path, headers):@@ -105,3 +197,19 @@ async def test_secret_headers_reject_invalid_input(tmp_path, headers):)finally:runtime.close()++[email protected]("method", ["create", "get_or_create"])+async def test_named_secret_requires_hosted_runtime(tmp_path, method):+ runtime = boxlite.Boxlite(boxlite.Options(home_dir=str(tmp_path / "runtime")))+ try:+ with pytest.raises(+ boxlite.errors.UnsupportedError,+ match="Named secrets require a hosted runtime",+ ):+ await getattr(runtime, method)(+ boxlite.BoxOptions(image="alpine", secrets=[{"secret": "shared"}])+ )+ finally:+ runtime.close()diff --git a/src/boxlite/src/lib.rs b/src/boxlite/src/lib.rsindex 01dd5df52..44840a88f 100644--- a/src/boxlite/src/lib.rs+++ b/src/boxlite/src/lib.rs@@ -72,9 +72,10 @@ pub use runtime::advanced_options::{ResourceLimits, SecurityOptions,};pub use runtime::options::{- BoxArchive, BoxOptions, BoxliteOptions, CloneOptions, ExportOptions, ImageRegistry,- ImageRegistryAuth, ImageRegistryProxy, InboundNetworkConfig, NetworkMode, NetworkSpec,- OutboundNetworkConfig, PortProtocol, RegistryTransport, RootfsSpec, Secret, SnapshotOptions,+ BoxArchive, BoxOptions, BoxliteOptions, CloneOptions, CreateBoxOptions, ExportOptions,+ ImageRegistry, ImageRegistryAuth, ImageRegistryProxy, InboundNetworkConfig, NetworkMode,+ NetworkSpec, OutboundNetworkConfig, PortProtocol, RegistryTransport, RootfsSpec, Secret,+ SnapshotOptions,};/// Boxlite library version (from CARGO_PKG_VERSION at compile time).pub const VERSION: &str = env!("CARGO_PKG_VERSION");diff --git a/src/boxlite/src/rest/runtime.rs b/src/boxlite/src/rest/runtime.rsindex 3087b9de6..97acfb5e4 100644--- a/src/boxlite/src/rest/runtime.rs+++ b/src/boxlite/src/rest/runtime.rs@@ -7,7 +7,7 @@ use boxlite_shared::errors::{BoxliteError, BoxliteResult};use crate::metrics::RuntimeMetrics;use crate::runtime::advanced_options::SecurityOptions;use crate::runtime::backend::RuntimeBackend;-use crate::runtime::options::{BoxArchive, BoxOptions};+use crate::runtime::options::{BoxArchive, BoxOptions, SecretBinding};use crate::{BoxInfo, CheckpointKind, CheckpointOptions, LiteBox};use super::client::ApiClient;@@ -325,7 +325,7 @@ fn litebox_from_rest(rest_box: Arc<RestBox>) -> LiteBox {LiteBox::new(box_backend, network_backend, snapshot_backend)}-impl BoxOptions {+impl<S> crate::CreateBoxOptions<S> {/// The remote sibling of [`BoxOptions::sanitize`]: check these options/// against what a REST server accepts from a client, before any network I/O.///@@ -448,7 +448,11 @@ impl BoxOptions {#[async_trait::async_trait]impl RuntimeBackend for RestRuntime {- async fn create(&self, options: BoxOptions, name: Option<String>) -> BoxliteResult<LiteBox> {+ async fn create(+ &self,+ options: crate::CreateBoxOptions,+ name: Option<String>,+ ) -> BoxliteResult<LiteBox> {// A checkpoint source carries no other option: the server restores// the saved box, so this never builds a `CreateBoxRequest`.if let Some(checkpoint) = options.checkpoint_source()? {@@ -457,7 +461,12 @@ impl RuntimeBackend for RestRuntime {.await;}options.sanitize_remote()?;- options.validate_secrets()?;+ BoxOptions::validate_secret_entries(options.secrets.entries.iter().filter_map(|entry| {+ match entry {+ SecretBinding::Inline(secret) => Some(secret),+ SecretBinding::Named(_) => None,+ }+ }))?;// Validate only the caller's requested policy. An unset auto_stop means// "no auto-stop", so it must not borrow the server's default here —@@ -493,6 +502,12 @@ impl RuntimeBackend for RestRuntime {.await?;}+ // The hosted store accepts at most 64 total entries in a mixed request.+ if options.secrets.entries.len() > 64 && options.has_named_secrets() {+ return Err(BoxliteError::InvalidArgument(+ "secrets must contain at most 64 entries".into(),+ ));+ }let req = CreateBoxRequest::from_options(&options, name);let resp = self.client.create_box(&req).await?;let info = resp.to_box_info()?;@@ -502,7 +517,7 @@ impl RuntimeBackend for RestRuntime {async fn get_or_create(&self,- options: BoxOptions,+ options: crate::CreateBoxOptions,name: Option<String>,) -> BoxliteResult<(LiteBox, bool)> {if matches!(options.rootfs, crate::RootfsSpec::Checkpoint(_)) {@@ -529,6 +544,11 @@ impl RuntimeBackend for RestRuntime {let path = format!("/boxes/{box_name}");match self.client.get::<BoxResponse>(&path).await {Ok(response) => {+ if options.has_named_secrets() {+ return Err(BoxliteError::Unsupported(+ "cannot verify named secret bindings on an existing box".into(),+ ));+ }// TODO DISCUSS: Legacy read-write volumes retain name-based reuse without// verifying mount metadata; decide whether tighter protection is preferable.if uses_mounts_field_for_new_mountspec || has_read_only_mounts {@@ -933,7 +953,7 @@ mod tests {auto_delete: Some(1),..Default::default()};- let err = RuntimeBackend::create(&runtime, opts, None)+ let err = RuntimeBackend::create(&runtime, opts.into_entries(), None).await.err().expect("unreachable server must yield an error");@@ -953,10 +973,12 @@ mod tests {let runtime =RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();- let error = match RuntimeBackend::create(&runtime, capability_options(), None).await {- Err(error) => error,- Ok(_) => panic!("an old server must not silently ignore a capability policy"),- };+ let error =+ match RuntimeBackend::create(&runtime, capability_options().into_entries(), None).await+ {+ Err(error) => error,+ Ok(_) => panic!("an old server must not silently ignore a capability policy"),+ };assert!(matches!(error, BoxliteError::Unsupported(_)));assert_eq!(server.await.unwrap(), ["GET /v1/config HTTP/1.1"]);@@ -981,7 +1003,7 @@ mod tests {..Default::default()};- let error = match RuntimeBackend::create(&runtime, opts, None).await {+ let error = match RuntimeBackend::create(&runtime, opts.into_entries(), None).await {Err(error) => error,Ok(_) => panic!("an explicit, even empty, capability policy must still be probed for"),};@@ -1000,7 +1022,7 @@ mod tests {let runtime =RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();- RuntimeBackend::create(&runtime, capability_options(), None)+ RuntimeBackend::create(&runtime, capability_options().into_entries(), None).await.expect("create with a capability policy");@@ -1016,7 +1038,7 @@ mod tests {let runtime =RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();- RuntimeBackend::create(&runtime, BoxOptions::default(), None)+ RuntimeBackend::create(&runtime, BoxOptions::default().into_entries(), None).await.expect("create without a capability policy");@@ -1046,10 +1068,11 @@ mod tests {let runtime =RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();- let error = RuntimeBackend::create(&runtime, checkpoint_options("base"), None)- .await- .err()- .unwrap();+ let error =+ RuntimeBackend::create(&runtime, checkpoint_options("base").into_entries(), None)+ .await+ .err()+ .unwrap();assert!(error.to_string().contains("admitted-box"), "{error}");if code == "invalid_argument" {assert!(matches!(error, BoxliteError::InvalidArgument(_)));@@ -1342,10 +1365,13 @@ mod tests {let runtime =RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();- let created =- RuntimeBackend::create(&runtime, checkpoint_options("base"), Some("worker".into()))- .await- .expect("create from a checkpoint");+ let created = RuntimeBackend::create(+ &runtime,+ checkpoint_options("base").into_entries(),+ Some("worker".into()),+ )+ .await+ .expect("create from a checkpoint");assert_eq!(created.id().as_str(), "01HJK4TNRPQSXYZ8WM6NCVT9R5");let requests = server.await.unwrap();@@ -1363,7 +1389,7 @@ mod tests {let runtime =RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();- RuntimeBackend::create(&runtime, checkpoint_options("base"), None)+ RuntimeBackend::create(&runtime, checkpoint_options("base").into_entries(), None).await.expect("unnamed create from a checkpoint");@@ -1395,8 +1421,13 @@ mod tests {..checkpoint_options("base")},];+ let named = checkpoint_options("base").with_secret_reference("shared");+ assert!(matches!(+ RuntimeBackend::create(&runtime, named, None).await,+ Err(BoxliteError::InvalidArgument(_))+ ));for options in overridden {- let error = RuntimeBackend::create(&runtime, options, None)+ let error = RuntimeBackend::create(&runtime, options.into_entries(), None).await.err().expect("overrides must be refused");@@ -1405,12 +1436,22 @@ mod tests {}for (checkpoint, name) in [("bad/key", None), ("base", Some("bad/name".to_owned()))] {assert!(matches!(- RuntimeBackend::create(&runtime, checkpoint_options(checkpoint), name).await,+ RuntimeBackend::create(+ &runtime,+ checkpoint_options(checkpoint).into_entries(),+ name+ )+ .await,Err(BoxliteError::InvalidArgument(_))));}assert!(matches!(- RuntimeBackend::get_or_create(&runtime, checkpoint_options("base"), None).await,+ RuntimeBackend::get_or_create(+ &runtime,+ checkpoint_options("base").into_entries(),+ None+ )+ .await,Err(BoxliteError::Unsupported(_))));}@@ -1605,7 +1646,7 @@ mod tests {..Default::default()};- let error = RuntimeBackend::create(&runtime, opts, None)+ let error = RuntimeBackend::create(&runtime, opts.into_entries(), None).await.err().expect("REST runtime must reject a host-local custom kernel path");@@ -1625,7 +1666,7 @@ mod tests {..Default::default()};- let error = RuntimeBackend::create(&runtime, box_options, None)+ let error = RuntimeBackend::create(&runtime, box_options.into_entries(), None).await.err().expect("REST nested virtualization must be rejected before network I/O");@@ -1645,7 +1686,7 @@ mod tests {..Default::default()};- let error = RuntimeBackend::create(&runtime, box_options, None)+ let error = RuntimeBackend::create(&runtime, box_options.into_entries(), None).await.err().expect("REST engine selection must be rejected before network I/O");@@ -1669,7 +1710,7 @@ mod tests {..Default::default()};- let error = RuntimeBackend::create(&runtime, box_options, None)+ let error = RuntimeBackend::create(&runtime, box_options.into_entries(), None).await.err().expect("REST host bind mounts must be rejected before network I/O");@@ -1698,7 +1739,7 @@ mod tests {..Default::default()};- let error = match RuntimeBackend::create(&runtime, box_options, None).await {+ let error = match RuntimeBackend::create(&runtime, box_options.into_entries(), None).await {Err(error) => error,Ok(_) => panic!("unadvertised typed mounts must be rejected before creation"),};@@ -1727,7 +1768,7 @@ mod tests {..Default::default()};- let error = match RuntimeBackend::create(&runtime, box_options, None).await {+ let error = match RuntimeBackend::create(&runtime, box_options.into_entries(), None).await {Err(error) => error,Ok(_) => panic!("unadvertised read-only mounts must be rejected before creation"),};@@ -1760,7 +1801,7 @@ mod tests {..Default::default()};- RuntimeBackend::create(&runtime, options, None)+ RuntimeBackend::create(&runtime, options.into_entries(), None).await.expect("both advertised capabilities permit the create");@@ -1801,7 +1842,7 @@ mod tests {..Default::default()};- RuntimeBackend::create(&runtime, options, None)+ RuntimeBackend::create(&runtime, options.into_entries(), None).await.expect("writable typed mounts do not need the read-only capability");assert_eq!(@@ -1834,7 +1875,7 @@ mod tests {..Default::default()};- RuntimeBackend::create(&runtime, options, None)+ RuntimeBackend::create(&runtime, options.into_entries(), None).await.expect("advertised read-only support permits the legacy create");@@ -1880,10 +1921,14 @@ mod tests {RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();- let error = RuntimeBackend::get_or_create(&runtime, options, Some("named".into()))- .await- .err()- .expect("an old server must not reuse or create a mounted box");+ let error = RuntimeBackend::get_or_create(+ &runtime,+ options.into_entries(),+ Some("named".into()),+ )+ .await+ .err()+ .expect("an old server must not reuse or create a mounted box");assert!(matches!(error, BoxliteError::Unsupported(_)), "{error:?}");assert_eq!(server.await.unwrap(), ["GET /v1/config HTTP/1.1"]);}@@ -1905,7 +1950,7 @@ mod tests {};let (litebox, created) =- RuntimeBackend::get_or_create(&runtime, options, Some("named".into()))+ RuntimeBackend::get_or_create(&runtime, options.into_entries(), Some("named".into())).await.expect("legacy read-write volumes preserve name-based reuse");@@ -1954,10 +1999,14 @@ mod tests {RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();- let error = RuntimeBackend::get_or_create(&runtime, options, Some("named".into()))- .await- .err()- .expect("reuse must not assume the existing mount configuration matches");+ let error = RuntimeBackend::get_or_create(+ &runtime,+ options.into_entries(),+ Some("named".into()),+ )+ .await+ .err()+ .expect("reuse must not assume the existing mount configuration matches");assert!(matches!(error, BoxliteError::Unsupported(_)), "{error:?}");assert!(error.to_string().contains("mount configuration"), "{error}");@@ -1984,7 +2033,7 @@ mod tests {}],..Default::default()};- let request = CreateBoxRequest::from_options(&options, None);+ let request = CreateBoxRequest::from_options(&options.into_entries(), None);let json = serde_json::to_value(&request).unwrap();assert_eq!(@@ -2015,7 +2064,7 @@ mod tests {// localhost:1 refuses the connection, so reaching *any* transport// error is the proof that the mount cleared client-side validation.- let error = RuntimeBackend::create(&runtime, box_options, None)+ let error = RuntimeBackend::create(&runtime, box_options.into_entries(), None).await.err().expect("no server is listening on localhost:1");@@ -2062,7 +2111,7 @@ mod tests {let options = BoxliteRestOptions::new("http://localhost:1");let runtime = RestRuntime::new(&options).expect("failed to create REST runtime");- let error = RuntimeBackend::create(&runtime, BoxOptions::default(), None)+ let error = RuntimeBackend::create(&runtime, BoxOptions::default().into_entries(), None).await.err().expect("no server is listening on port 1, so this must still fail");@@ -2085,7 +2134,7 @@ mod tests {..Default::default()};- let error = RuntimeBackend::create(&runtime, box_options, None)+ let error = RuntimeBackend::create(&runtime, box_options.into_entries(), None).await.err().expect("unadvertised guest privilege must be rejected");@@ -2109,9 +2158,13 @@ mod tests {if explicit_default {options.advanced.set_privileged(false);}- RuntimeBackend::create(&runtime, options.clone(), Some("privilege-contract".into()))- .await- .unwrap();+ RuntimeBackend::create(+ &runtime,+ options.clone().into_entries(),+ Some("privilege-contract".into()),+ )+ .await+ .unwrap();}for (headers, body) in server.await.unwrap() {assert_eq!(headers.lines().next(), Some("POST /v1/boxes HTTP/1.1"));@@ -2151,14 +2204,15 @@ mod tests {}],..Default::default()};- RuntimeBackend::create(&runtime, options.clone(), None)+ RuntimeBackend::create(&runtime, options.clone().into_entries(), None).await.unwrap();- options.secrets[0].headers = Some(std::collections::BTreeMap::from([(+ let inline = &mut options.secrets[0];+ inline.headers = Some(std::collections::BTreeMap::from([("x-goog-api-key".into(),"{value}".into(),)]));- RuntimeBackend::create(&runtime, options, None)+ RuntimeBackend::create(&runtime, options.into_entries(), None).await.unwrap();@@ -2196,6 +2250,86 @@ mod tests {assert_eq!(before, with_header);}+ #[tokio::test]+ async fn create_accepts_inline_secret_and_inferred_default_options() {+ let (port, server) = capture_server(vec![(201, BOX_RESPONSE), (201, BOX_RESPONSE)]).await;+ let runtime = crate::BoxliteRuntime::rest(BoxliteRestOptions::new(format!(+ "http://127.0.0.1:{port}"+ )))+ .unwrap();+ let secret = crate::Secret {+ name: "inline".into(),+ value: "fixture".into(),+ hosts: vec!["api.example".into()],+ placeholder: "<BOXLITE_SECRET:inline>".into(),+ headers: Some(std::collections::BTreeMap::from([(+ "X-Key".into(),+ "{value}".into(),+ )])),+ };+ let expected = serde_json::to_value(&secret).unwrap();+ let mut options = crate::BoxOptions::default();+ let inline: &mut Vec<crate::Secret> = &mut options.secrets;+ inline.push(secret);+ runtime.create(options, None).await.unwrap();+ runtime.create(Default::default(), None).await.unwrap();+ let requests = server.await.unwrap();+ assert!(+ requests+ .iter()+ .all(|(headers, _)| headers.lines().next() == Some("POST /v1/boxes HTTP/1.1"))+ );+ let body = |i: usize| serde_json::from_str::<serde_json::Value>(&requests[i].1).unwrap();+ assert_eq!(body(0)["secrets"], serde_json::json!([expected]));+ assert!(body(1).get("secrets").is_none());+ }++ #[tokio::test]+ async fn create_preserves_mixed_secret_order() {+ let (port, server) = capture_server(vec![(201, BOX_RESPONSE)]).await;+ let runtime = crate::BoxliteRuntime::rest(BoxliteRestOptions::new(format!(+ "http://127.0.0.1:{port}"+ )))+ .unwrap();+ let inline = |name: &str| crate::Secret {+ name: name.into(),+ value: "test".into(),+ hosts: vec![format!("{name}.example")],+ placeholder: format!("<BOXLITE_SECRET:{name}>"),+ headers: Some(std::collections::BTreeMap::from([(+ "X-Key".into(),+ "{value}".into(),+ )])),+ };+ let mut options = BoxOptions {+ secrets: vec![inline("first")],+ ..Default::default()+ }+ .with_secret_reference("shared");+ options.secrets.push(inline("second"));+ let options = options.with_secret_reference(String::from("last"));+ runtime.create(options, None).await.unwrap();+ let requests = server.await.unwrap();+ assert_eq!(requests.len(), 1);+ assert_eq!(+ requests[0].0.lines().next(),+ Some("POST /v1/boxes HTTP/1.1")+ );+ let body: serde_json::Value = serde_json::from_str(&requests[0].1).unwrap();+ let entries = body["secrets"].as_array().unwrap();+ assert_eq!(entries.len(), 4);+ assert_eq!(entries[0]["name"], "first");+ assert_eq!(entries[1], serde_json::json!({"secret":"shared"}));+ assert_eq!(entries[2]["name"], "second");+ assert_eq!(entries[3], serde_json::json!({"secret":"last"}));+ let mut oversized = BoxOptions::default().with_secret_reference("shared");+ for _ in 1..65 {+ oversized = oversized.with_secret_reference("shared");+ }+ let error = runtime.create(oversized, None).await.err().unwrap();+ assert!(matches!(error, BoxliteError::InvalidArgument(_)));+ }+#[tokio::test]async fn advertised_privileged_creates_guest_box_and_rechecks_support() {let (port, server) = capture_server(vec![@@ -2208,10 +2342,10 @@ mod tests {RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();let mut opts = BoxOptions::default();opts.advanced.set_privileged(true);- RuntimeBackend::create(&runtime, opts.clone(), None)+ RuntimeBackend::create(&runtime, opts.clone().into_entries(), None).await.unwrap();- let error = RuntimeBackend::create(&runtime, opts, None)+ let error = RuntimeBackend::create(&runtime, opts.into_entries(), None).await.err().unwrap();@@ -2252,8 +2386,12 @@ mod tests {.unwrap();let mut options = BoxOptions::default();options.advanced.set_privileged(requested);- let result =- RuntimeBackend::get_or_create(&runtime, options, Some("named".into())).await;+ let result = RuntimeBackend::get_or_create(+ &runtime,+ options.into_entries(),+ Some("named".into()),+ )+ .await;let correct = match result {Ok((litebox, created)) => {reported == requested@@ -2292,10 +2430,14 @@ mod tests {);let mut options = BoxOptions::default();options.advanced.set_privileged(requested);- let error = RuntimeBackend::get_or_create(&runtime, options, Some("named".into()))- .await- .err()- .expect("unknown privilege must not be reused");+ let error = RuntimeBackend::get_or_create(+ &runtime,+ options.into_entries(),+ Some("named".into()),+ )+ .await+ .err()+ .expect("unknown privilege must not be reused");assert!(matches!(error, BoxliteError::Unsupported(_)));assert!(error.to_string().contains("privileged"));assert_eq!(server.await.unwrap(), ["GET /v1/boxes/named HTTP/1.1"; 2]);@@ -2339,9 +2481,10 @@ mod tests {RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();let mut options = BoxOptions::default();options.advanced.set_privileged(true);- let (_, created) = RuntimeBackend::get_or_create(&runtime, options, Some("named".into()))- .await- .unwrap();+ let (_, created) =+ RuntimeBackend::get_or_create(&runtime, options.into_entries(), Some("named".into()))+ .await+ .unwrap();assert!(created);assert_eq!(server.await.unwrap(),@@ -2377,7 +2520,7 @@ mod tests {..Default::default()};- let error = RuntimeBackend::create(&runtime, box_options, None)+ let error = RuntimeBackend::create(&runtime, box_options.into_entries(), None).await.err().expect("REST network rate limits must be rejected before network I/O");@@ -2406,7 +2549,7 @@ mod tests {..Default::default()};- let error = RuntimeBackend::create(&runtime, box_options, None)+ let error = RuntimeBackend::create(&runtime, box_options.into_entries(), None).await.err().expect("nothing is listening, so the create cannot succeed");@@ -2428,7 +2571,7 @@ mod tests {..Default::default()};- let error = RuntimeBackend::create(&runtime, box_options, None)+ let error = RuntimeBackend::create(&runtime, box_options.into_entries(), None).await.err().expect("REST mount isolation must be rejected before network I/O");@@ -2449,7 +2592,7 @@ mod tests {..Default::default()};- let error = RuntimeBackend::create(&runtime, box_options, None)+ let error = RuntimeBackend::create(&runtime, box_options.into_entries(), None).await.err().expect("REST health checks must be rejected before network I/O");@@ -2474,10 +2617,14 @@ mod tests {..Default::default()};- let error = RuntimeBackend::get_or_create(&runtime, opts, Some("custom".to_string()))- .await- .err()- .expect("REST runtime must reject a custom kernel before lookup");+ let error = RuntimeBackend::get_or_create(+ &runtime,+ opts.into_entries(),+ Some("custom".to_string()),+ )+ .await+ .err()+ .expect("REST runtime must reject a custom kernel before lookup");assert!(matches!(error, BoxliteError::Unsupported(_)));assert!(error.to_string().contains("local runtime"));@@ -2494,11 +2641,14 @@ mod tests {..Default::default()};- let error =- RuntimeBackend::get_or_create(&runtime, box_options, Some("nested".to_string()))- .await- .err()- .expect("REST nested virtualization must be rejected before network I/O");+ let error = RuntimeBackend::get_or_create(+ &runtime,+ box_options.into_entries(),+ Some("nested".to_string()),+ )+ .await+ .err()+ .expect("REST nested virtualization must be rejected before network I/O");assert!(matches!(error, BoxliteError::Unsupported(_)));assert!(error.to_string().contains("local runtime"));diff --git a/src/boxlite/src/rest/types.rs b/src/boxlite/src/rest/types.rsindex a0c290a98..90cb00681 100644--- a/src/boxlite/src/rest/types.rs+++ b/src/boxlite/src/rest/types.rs@@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize};use crate::litebox::BoxStatus;use crate::litebox::snapshot_mgr::SnapshotInfo;use crate::runtime::advanced_options::ContainerCapabilities;-use crate::runtime::options::{CloneOptions, ExportOptions, SnapshotOptions};+use crate::runtime::options::{CloneOptions, ExportOptions, SecretBinding, SnapshotOptions};// ============================================================================// Error Model@@ -150,7 +150,7 @@ pub(crate) struct CreateBoxRequest {#[serde(skip_serializing_if = "Option::is_none")]pub user: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]- pub secrets: Option<Vec<CreateBoxSecret>>,+ pub secrets: Option<Vec<SecretEntry>>,#[serde(skip_serializing_if = "Option::is_none")]pub volumes: Option<Vec<CreateBoxVolumeSpec>>,#[serde(skip_serializing_if = "Option::is_none")]@@ -173,11 +173,25 @@ pub(crate) struct CreateBoxRequest {pub auto_resume: Option<bool>,}+impl From<&crate::Secret> for SecretEntry {+ fn from(secret: &crate::Secret) -> Self {+ Self::Inline(secret.into())+ }+}++impl From<&SecretBinding> for SecretEntry {+ fn from(entry: &SecretBinding) -> Self {+ match entry {+ SecretBinding::Inline(secret) => secret.into(),+ SecretBinding::Named(name) => Self::Named {+ secret: name.clone(),+ },+ }+ }+}+impl CreateBoxRequest {- pub fn from_options(- options: &crate::runtime::options::BoxOptions,- name: Option<String>,- ) -> Self {+ pub fn from_options(options: &crate::CreateBoxOptions, name: Option<String>) -> Self {use crate::runtime::options::RootfsSpec;let (image, rootfs_path) = match &options.rootfs {@@ -194,10 +208,10 @@ impl CreateBoxRequest {Some(options.env.iter().cloned().collect())};- let secrets = if options.secrets.is_empty() {+ let secrets = if options.secrets.entries.is_empty() {None} else {- Some(options.secrets.iter().map(CreateBoxSecret::from).collect())+ Some(options.secrets.entries.iter().map(Into::into).collect())};let volumes = if options.volumes.is_empty() {None@@ -417,6 +431,13 @@ impl CreateBoxNetworkSpec {}}+#[derive(Debug, Serialize)]+#[serde(untagged)]+pub(crate) enum SecretEntry {+ Inline(CreateBoxSecret),+ Named { secret: String },+}+#[derive(Debug, Serialize)]pub(crate) struct CreateBoxSecret {pub name: String,@@ -1124,8 +1145,8 @@ mod tests {},..Default::default()};- let mut req = CreateBoxRequest::from_options(&opts, Some("mybox".into()));- req.secrets = Some(vec![CreateBoxSecret {+ let mut req = CreateBoxRequest::from_options(&opts.into_entries(), Some("mybox".into()));+ req.secrets = Some(vec![SecretEntry::Inline(CreateBoxSecret {name: "openai".into(),value: "sk-test".into(),hosts: vec!["api.openai.com".into()],@@ -1134,7 +1155,7 @@ mod tests {"Authorization".into(),"Bearer {value}".into(),)])),- }]);+ })]);req.auto_stop = Some(900);req.auto_delete = Some(604800);@@ -1182,7 +1203,7 @@ mod tests {auto_delete: Some(604800),..Default::default()};- let req = CreateBoxRequest::from_options(&opts, Some("test-box".into()));+ let req = CreateBoxRequest::from_options(&opts.into_entries(), Some("test-box".into()));assert_eq!(req.name.as_deref(), Some("test-box"));assert_eq!(req.image.as_deref(), Some("alpine:latest"));assert!(req.rootfs_path.is_none());@@ -1214,7 +1235,7 @@ mod tests {assert_eq!(req.auto_stop, Some(1800));assert_eq!(req.auto_delete, Some(604800));assert_eq!(- req.secrets.as_ref().unwrap()[0].placeholder,+ serde_json::to_value(&req.secrets.as_ref().unwrap()[0]).unwrap()["placeholder"],"<BOXLITE_SECRET:openai>");}@@ -1233,7 +1254,7 @@ mod tests {..Default::default()};- let req = CreateBoxRequest::from_options(&opts, None);+ let req = CreateBoxRequest::from_options(&opts.into_entries(), None);let advanced = req.advanced.as_ref().expect("custom policy is serialized");let capabilities = advanced.capabilities.as_ref().unwrap();assert_eq!(capabilities.add, ["SYS_ADMIN"]);@@ -1245,7 +1266,7 @@ mod tests {serde_json::json!({"add": ["SYS_ADMIN"], "drop": ["CAP_NET_RAW"]}));- let defaults = CreateBoxRequest::from_options(&BoxOptions::default(), None);+ let defaults = CreateBoxRequest::from_options(&BoxOptions::default().into_entries(), None);let defaults_json = serde_json::to_value(defaults).expect("serialize defaults");assert!(defaults_json.get("advanced").is_none());}@@ -1264,7 +1285,7 @@ mod tests {..Default::default()};- let req = CreateBoxRequest::from_options(&opts, None);+ let req = CreateBoxRequest::from_options(&opts.into_entries(), None);assert!(req.advanced.is_some(),"an explicit empty policy must still be serialized"@@ -1319,7 +1340,7 @@ mod tests {..Default::default()};- let req = CreateBoxRequest::from_options(&opts, None);+ let req = CreateBoxRequest::from_options(&opts.into_entries(), None);let volume = &req.volumes.as_ref().unwrap()[0];assert_eq!(volume.managed_volume, reference);assert_eq!(volume.guest_path, "/data");@@ -1343,7 +1364,7 @@ mod tests {auto_delete: None,..Default::default()};- let req = CreateBoxRequest::from_options(&opts, None);+ let req = CreateBoxRequest::from_options(&opts.into_entries(), None);assert_eq!(req.auto_stop, None);assert_eq!(req.auto_delete, None);}@@ -1354,7 +1375,7 @@ mod tests {auto_delete: Some(3600),..Default::default()};- let req = CreateBoxRequest::from_options(&modern, None);+ let req = CreateBoxRequest::from_options(&modern.into_entries(), None);assert_eq!(req.auto_stop, Some(900));assert_eq!(req.auto_delete, Some(3600));}@@ -1369,7 +1390,7 @@ mod tests {..Default::default()};- let req = CreateBoxRequest::from_options(&opts, None);+ let req = CreateBoxRequest::from_options(&opts.into_entries(), None);// inbound at default → legacy flat shape.let json = serde_json::to_value(&req).unwrap();assert_eq!(json["network"]["mode"], "disabled");@@ -1390,7 +1411,10 @@ mod tests {..Default::default()};- let disabled = CreateBoxRequest::from_options(&with_inbound(NetworkSpec::Disabled), None);+ let disabled = CreateBoxRequest::from_options(+ &with_inbound(NetworkSpec::Disabled).into_entries(),+ None,+ );let json = serde_json::to_value(&disabled).unwrap();assert_eq!(json["network"]["mode"], "enabled");assert!(json["network"]["inbound"].is_null());@@ -1398,7 +1422,8 @@ mod tests {let enabled = CreateBoxRequest::from_options(&with_inbound(NetworkSpec::Enabled {allow_net: Vec::new(),- }),+ })+ .into_entries(),None,);let json = serde_json::to_value(&enabled).unwrap();@@ -1429,7 +1454,7 @@ mod tests {advanced,..Default::default()};- let req = CreateBoxRequest::from_options(&opts, None);+ let req = CreateBoxRequest::from_options(&opts.into_entries(), None);let json = serde_json::to_string(&req).unwrap();assert!(!json.contains("security"),@@ -1454,7 +1479,7 @@ mod tests {advanced,..Default::default()};- let req = CreateBoxRequest::from_options(&opts, None);+ let req = CreateBoxRequest::from_options(&opts.into_entries(), None);let json = serde_json::to_string(&req).unwrap();assert!(!json.contains("rate_limit") && !json.contains("kbps"),diff --git a/src/boxlite/src/runtime/backend.rs b/src/boxlite/src/runtime/backend.rsindex ae5dac719..8a27e7065 100644--- a/src/boxlite/src/runtime/backend.rs+++ b/src/boxlite/src/runtime/backend.rs@@ -15,7 +15,7 @@ use crate::litebox::{};use crate::metrics::{BoxMetrics, RuntimeMetrics};use crate::runtime::options::{- BoxArchive, BoxOptions, CloneOptions, ExportOptions, InboundNetworkConfig,+ BoxArchive, CloneOptions, CreateBoxOptions, ExportOptions, InboundNetworkConfig,OutboundNetworkConfig, SnapshotOptions,};use crate::runtime::types::BoxInfo;@@ -36,11 +36,15 @@ use super::id::BoxID;)]#[async_trait]pub(crate) trait RuntimeBackend: Send + Sync {- async fn create(&self, options: BoxOptions, name: Option<String>) -> BoxliteResult<LiteBox>;+ async fn create(+ &self,+ options: CreateBoxOptions,+ name: Option<String>,+ ) -> BoxliteResult<LiteBox>;async fn get_or_create(&self,- options: BoxOptions,+ options: CreateBoxOptions,name: Option<String>,) -> BoxliteResult<(LiteBox, bool)>;diff --git a/src/boxlite/src/runtime/core.rs b/src/boxlite/src/runtime/core.rsindex 18dccb391..7a1b4c203 100644--- a/src/boxlite/src/runtime/core.rs+++ b/src/boxlite/src/runtime/core.rs@@ -3,13 +3,15 @@use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, OnceLock};+#[cfg(test)]+use crate::BoxOptions;use crate::experimental::ExperimentalFeatures;use crate::litebox::LiteBox;use crate::metrics::RuntimeMetrics;use crate::runtime::backend::RuntimeBackend;use crate::runtime::checkpoints::{CheckpointBackend, CheckpointHandle};use crate::runtime::images::ImageBackend;-use crate::runtime::options::{BoxArchive, BoxOptions, BoxliteOptions};+use crate::runtime::options::{BoxArchive, BoxliteOptions, CreateBoxOptions, SecretBindings};use crate::runtime::registries::RegistryBackend;use crate::runtime::rt_impl::{LocalRuntime, RuntimeImpl};use crate::runtime::signal_handler::install_signal_handler;@@ -330,13 +332,13 @@ impl BoxliteRuntime {/// The box is immediately visible in `list_info()` after creation.pub async fn create(&self,- options: BoxOptions,+ options: CreateBoxOptions<impl Into<SecretBindings>>,name: Option<String>,) -> BoxliteResult<LiteBox> {// Reject incompatible option combinations at the create boundary (fail// here, not at start), uniformly for the local and REST backends.options.sanitize_create()?;- self.backend.create(options, name).await+ self.backend.create(options.into_entries(), name).await}/// Get an existing box by name, or create a new one if it doesn't exist.@@ -347,11 +349,13 @@ impl BoxliteRuntime {/// compatible with the existing box.pub async fn get_or_create(&self,- options: BoxOptions,+ options: CreateBoxOptions<impl Into<SecretBindings>>,name: Option<String>,) -> BoxliteResult<(LiteBox, bool)> {options.sanitize_create()?;- self.backend.get_or_create(options, name).await+ self.backend+ .get_or_create(options.into_entries(), name)+ .await}/// Get a handle to an existing box by ID or name.diff --git a/src/boxlite/src/runtime/options.rs b/src/boxlite/src/runtime/options.rsindex 8171a04f7..b3cfc3f74 100644--- a/src/boxlite/src/runtime/options.rs+++ b/src/boxlite/src/runtime/options.rs@@ -376,10 +376,18 @@ mod registry_options_tests {}}-/// Options used when constructing a box.+/// Box options with inline secret values. Use [`BoxOptions::with_secret_reference`] to+/// include hosted organization secrets when creating a box.+pub type BoxOptions = CreateBoxOptions<Vec<Secret>>;++/// Box creation options with an ordered list of secret entries.#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]-#[serde(default)]-pub struct BoxOptions {+#[serde(+ rename = "BoxOptions",+ default = "CreateBoxOptions::defaults",+ bound(deserialize = "S: Default + serde::Deserialize<'de>")+)]+pub struct CreateBoxOptions<S = SecretBindings> {/// CPU allocation; fractional values require a Linux execution host./// For REST runtimes, this requirement applies to the server.#[serde(serialize_with = "super::cpu_count::serialize_optional")]@@ -499,7 +507,7 @@ pub struct BoxOptions {#[serde(default)]pub tty: bool,- /// Secrets for MITM proxy injection into outbound HTTPS requests.+ /// Inline secrets and hosted organization secret references, in request order.////// When the box makes an HTTPS request to a host a secret lists, the proxy/// overwrites the secret's configured header only if the original request@@ -508,7 +516,42 @@ pub struct BoxOptions {/// The placeholder (e.g., `<BOXLITE_SECRET:openai>`) is only a dummy value/// for the guest's environment; the real value never enters the VM.#[serde(default)]- pub secrets: Vec<Secret>,+ pub secrets: S,+}++/// Ordered secrets for a Box creation request that can include organization references.+#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]+#[serde(transparent)]+pub struct SecretBindings {+ pub(crate) entries: Vec<SecretBinding>,+}++#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]+pub(crate) enum SecretBinding {+ #[serde(rename = "secret")]+ Named(String),+ #[serde(untagged)]+ Inline(Secret),+}++impl SecretBindings {+ /// Append a Box-specific value after the existing bindings.+ pub fn push(&mut self, secret: Secret) {+ self.entries.push(SecretBinding::Inline(secret));+ }++ /// Append an organization secret by name after the existing bindings.+ pub fn push_reference(&mut self, name: impl Into<String>) {+ self.entries.push(SecretBinding::Named(name.into()));+ }+}++impl From<Vec<Secret>> for SecretBindings {+ fn from(secrets: Vec<Secret>) -> Self {+ Self {+ entries: secrets.into_iter().map(SecretBinding::Inline).collect(),+ }+ }}/// A secret for MITM proxy injection.@@ -678,9 +721,29 @@ fn default_detach() -> bool {false}-#[allow(deprecated)]impl Default for BoxOptions {fn default() -> Self {+ Self::defaults()+ }+}++impl<S> CreateBoxOptions<S> {+ /// Append a hosted organization secret by name. Multiple calls preserve their order.+ #[must_use]+ pub fn with_secret_reference(self, name: impl Into<String>) -> CreateBoxOptions+ where+ S: Into<SecretBindings>,+ {+ let mut options = self.into_entries();+ options.secrets.push_reference(name);+ options+ }++ #[allow(deprecated)]+ fn defaults() -> Self+ where+ S: Default,+ {Self {cpus: None,memory_mib: None,@@ -703,12 +766,50 @@ impl Default for BoxOptions {cmd: None,user: None,tty: false,- secrets: Vec::new(),+ secrets: S::default(),}}-}-impl BoxOptions {+ #[allow(deprecated)]+ fn split_secrets<T: Default>(self) -> (CreateBoxOptions<T>, S) {+ (+ CreateBoxOptions {+ cpus: self.cpus,+ memory_mib: self.memory_mib,+ disk_size_gb: self.disk_size_gb,+ working_dir: self.working_dir,+ env: self.env,+ rootfs: self.rootfs,+ volumes: self.volumes,+ mounts: self.mounts,+ network: self.network,+ inbound_network: self.inbound_network,+ ports: self.ports,+ auto_remove: self.auto_remove,+ auto_stop: self.auto_stop,+ auto_delete: self.auto_delete,+ auto_resume: self.auto_resume,+ detach: self.detach,+ advanced: self.advanced,+ entrypoint: self.entrypoint,+ cmd: self.cmd,+ user: self.user,+ tty: self.tty,+ secrets: T::default(),+ },+ self.secrets,+ )+ }++ pub(crate) fn into_entries(self) -> CreateBoxOptions+ where+ S: Into<SecretBindings>,+ {+ let (mut options, entries) = self.split_secrets();+ options.secrets = entries.into();+ options+ }+/// Resolve the modern and deprecated deletion inputs to one policy.#[allow(deprecated)]pub(crate) fn effective_auto_delete(&self) -> u32 {@@ -729,13 +830,16 @@ impl BoxOptions {/// accepts no overrides. Any other option that differs from its default is/// therefore rejected here instead of being dropped on the wire.#[cfg(feature = "rest")]- pub(crate) fn checkpoint_source(&self) -> BoxliteResult<Option<&str>> {+ pub(crate) fn checkpoint_source(&self) -> BoxliteResult<Option<&str>>+ where+ S: Default + serde::Serialize,+ {let RootfsSpec::Checkpoint(checkpoint) = &self.rootfs else {return Ok(None);};let inherited = Self {rootfs: self.rootfs.clone(),- ..Self::default()+ ..Self::defaults()};let serialized = |options: &Self| {serde_json::to_value(options).map_err(|error| {@@ -863,13 +967,52 @@ impl BoxOptions {Ok(())}+}++impl CreateBoxOptions {+ #[cfg(feature = "rest")]+ pub(crate) fn has_named_secrets(&self) -> bool {+ self.secrets+ .entries+ .iter()+ .any(|entry| matches!(entry, SecretBinding::Named(_)))+ }+}+impl From<BoxOptions> for CreateBoxOptions {+ fn from(options: BoxOptions) -> Self {+ options.into_entries()+ }+}++impl TryFrom<CreateBoxOptions> for BoxOptions {+ type Error = BoxliteError;++ fn try_from(request: CreateBoxOptions) -> BoxliteResult<Self> {+ let (mut options, entries) = request.split_secrets();+ options.secrets = entries+ .entries+ .into_iter()+ .map(|entry| match entry {+ SecretBinding::Inline(secret) => Ok(secret),+ SecretBinding::Named(_) => Err(BoxliteError::Unsupported(+ "Named secrets require a hosted runtime".into(),+ )),+ })+ .collect::<BoxliteResult<Vec<_>>>()?;+ Ok(options)+ }+}++impl BoxOptions {/// `(host, header)` pairs that more than one secret writes. The proxy lets/// the last secret win for such a pair.- fn secret_header_conflicts(&self) -> Vec<(String, String)> {+ fn secret_header_conflicts<'a>(+ secrets: impl Iterator<Item = &'a Secret>,+ ) -> Vec<(String, String)> {let mut seen = std::collections::HashSet::new();let mut conflicts = Vec::new();- for secret in &self.secrets {+ for secret in secrets {let Some(headers) = &secret.headers else {continue;};@@ -900,9 +1043,13 @@ impl BoxOptions {/// Validate new secrets, including ingestion-only host and conflict rules.pub(crate) fn validate_secrets(&self) -> BoxliteResult<()> {- use boxlite_shared::errors::BoxliteError;+ Self::validate_secret_entries(self.secrets.iter())+ }- for secret in &self.secrets {+ pub(crate) fn validate_secret_entries<'a>(+ secrets: impl Iterator<Item = &'a Secret> + Clone,+ ) -> BoxliteResult<()> {+ for secret in secrets.clone() {let name = &secret.name;if secret.hosts.is_empty() || secret.hosts.iter().any(String::is_empty) {return Err(BoxliteError::InvalidArgument(format!(@@ -920,7 +1067,7 @@ impl BoxOptions {secret.validate_headers()?;}- if let Some((host, header)) = self.secret_header_conflicts().into_iter().next() {+ if let Some((host, header)) = Self::secret_header_conflicts(secrets).into_iter().next() {return Err(BoxliteError::InvalidArgument(format!("conflicting secrets on host {host:?} for header {header:?}: \multiple secrets configure the same header"@@ -951,7 +1098,7 @@ impl BoxOptions {self.validate_local_cpu_support()?;self.sanitize_common()?;- for (host, header) in self.secret_header_conflicts() {+ for (host, header) in Self::secret_header_conflicts(self.secrets.iter()) {tracing::warn!(host,header,@@ -976,7 +1123,9 @@ impl BoxOptions {Ok(())}+}+impl<S> CreateBoxOptions<S> {/// Normalize the public resource quantity before deriving quotas or topology.pub(crate) fn cpu_count(&self) -> BoxliteResult<Option<super::cpu_count::CpuCount>> {self.cpus.map(super::cpu_count::CpuCount::new).transpose()@@ -3297,11 +3446,26 @@ mod tests {let opts = BoxOptions {secrets: vec![test_secret()],..Default::default()- };- let json = serde_json::to_string(&opts).unwrap();- let deserialized: BoxOptions = serde_json::from_str(&json).unwrap();- assert_eq!(deserialized.secrets.len(), 1);- assert_eq!(deserialized.secrets[0], test_secret());+ }+ .with_secret_reference("shared");+ let json = serde_json::to_value(&opts).unwrap();+ assert_eq!(+ json["secrets"],+ serde_json::json!([test_secret(), {"secret": "shared"}])+ );+ let deserialized: CreateBoxOptions = serde_json::from_value(json).unwrap();+ assert_eq!(deserialized.secrets, opts.secrets);+ }++ #[test]+ fn local_secret_validation_rejects_a_stored_organization_reference() {+ let opts = BoxOptions::default().with_secret_reference("shared");+ let stored = serde_json::to_value(&opts).unwrap();+ assert!(serde_json::from_value::<BoxOptions>(stored).is_err());+ assert!(matches!(+ BoxOptions::try_from(opts),+ Err(BoxliteError::Unsupported(_))+ ));}#[test]@@ -3619,7 +3783,10 @@ mod tests {// A stored box from before the rule stays bootable.opts.sanitize_persisted().unwrap();- assert_eq!(opts.secret_header_conflicts().len(), 1);+ assert_eq!(+ BoxOptions::secret_header_conflicts(opts.secrets.iter()).len(),+ 1+ );}#[test]diff --git a/src/boxlite/src/runtime/rt_impl.rs b/src/boxlite/src/runtime/rt_impl.rsindex a30e37ca6..2e208ec24 100644--- a/src/boxlite/src/runtime/rt_impl.rs+++ b/src/boxlite/src/runtime/rt_impl.rs@@ -2097,17 +2097,23 @@ async fn sanitize_local_options(#[async_trait::async_trait]impl super::backend::RuntimeBackend for LocalRuntime {- async fn create(&self, options: BoxOptions, name: Option<String>) -> BoxliteResult<LiteBox> {- let options = sanitize_local_options(&self.0.experimental_features, options).await?;+ async fn create(+ &self,+ options: crate::CreateBoxOptions,+ name: Option<String>,+ ) -> BoxliteResult<LiteBox> {+ let options =+ sanitize_local_options(&self.0.experimental_features, options.try_into()?).await?;self.0.create(options, name).await}async fn get_or_create(&self,- options: BoxOptions,+ options: crate::CreateBoxOptions,name: Option<String>,) -> BoxliteResult<(LiteBox, bool)> {- let options = sanitize_local_options(&self.0.experimental_features, options).await?;+ let options =+ sanitize_local_options(&self.0.experimental_features, options.try_into()?).await?;self.0.get_or_create(options, name).await}@@ -2407,7 +2413,7 @@ mod tests {cpus: Some(cpus),..Default::default()};- let error = RuntimeBackend::create(&local, options, Some(name.clone()))+ let error = RuntimeBackend::create(&local, options.into_entries(), Some(name.clone())).await.err().expect("cpus outside 0.125..=16 must be rejected at create");@@ -2432,7 +2438,7 @@ mod tests {cpus,..Default::default()};- RuntimeBackend::create(&local, options, None)+ RuntimeBackend::create(&local, options.into_entries(), None).await.unwrap_or_else(|error| panic!("cpus {cpus:?} must be accepted: {error}"));}@@ -2457,16 +2463,23 @@ mod tests {..Default::default()};- let (_, created) =- RuntimeBackend::get_or_create(&local, request(), Some("legacy".to_string()))- .await- .expect("an existing box is reused whatever cpus it was created with");+ let (_, created) = RuntimeBackend::get_or_create(+ &local,+ request().into_entries(),+ Some("legacy".to_string()),+ )+ .await+ .expect("an existing box is reused whatever cpus it was created with");assert!(!created);- let error = RuntimeBackend::get_or_create(&local, request(), Some("fresh".to_string()))- .await- .err()- .expect("a new box beyond the guest kernel's vCPUs must be rejected");+ let error = RuntimeBackend::get_or_create(+ &local,+ request().into_entries(),+ Some("fresh".to_string()),+ )+ .await+ .err()+ .expect("a new box beyond the guest kernel's vCPUs must be rejected");assert!(matches!(error, BoxliteError::InvalidArgument(_)),"{error:?}"@@ -2776,7 +2789,8 @@ mod tests {volumes: vec![VolumeSpec::managed_volume("workspace", "/workspace")],auto_delete: Some(0),..Default::default()- },+ }+ .into_entries(),None,).await@@ -2802,7 +2816,8 @@ mod tests {],auto_delete: Some(0),..Default::default()- },+ }+ .into_entries(),None,).await@@ -2821,7 +2836,8 @@ mod tests {],auto_delete: Some(0),..Default::default()- },+ }+ .into_entries(),None,).await@@ -2853,17 +2869,22 @@ mod tests {async fn get_or_create_adopts_an_existing_box_despite_a_pre_rule_secret() {let (runtime, _dir) = create_test_runtime();let local = LocalRuntime(Arc::clone(&runtime));- RuntimeBackend::create(&local, BoxOptions::default(), Some("replayed".into()))- .await- .expect("create a box without secrets");+ RuntimeBackend::create(+ &local,+ BoxOptions::default().into_entries(),+ Some("replayed".into()),+ )+ .await+ .expect("create a box without secrets");let options = BoxOptions {secrets: vec![secret_without_hosts()],..Default::default()};- let (_, created) = RuntimeBackend::get_or_create(&local, options, Some("replayed".into()))- .await- .expect("adopting an existing box must not validate the request's secrets");+ let (_, created) =+ RuntimeBackend::get_or_create(&local, options.into_entries(), Some("replayed".into()))+ .await+ .expect("adopting an existing box must not validate the request's secrets");assert!(!created);}@@ -2875,10 +2896,11 @@ mod tests {secrets: vec![secret_without_hosts()],..Default::default()};- let error = RuntimeBackend::get_or_create(&local, options, Some("new-box".into()))- .await- .err()- .expect("a new box must hold to the secret rules");+ let error =+ RuntimeBackend::get_or_create(&local, options.into_entries(), Some("new-box".into()))+ .await+ .err()+ .expect("a new box must hold to the secret rules");assert!(matches!(error, BoxliteError::InvalidArgument(_)),"{error:?}"@@ -4432,10 +4454,13 @@ mod tests {cpus: Some(saved_cpus),..Default::default()};- let (created, is_new) =- RuntimeBackend::get_or_create(&local, options.clone(), Some("fractional".into()))- .await- .unwrap();+ let (created, is_new) = RuntimeBackend::get_or_create(+ &local,+ options.clone().into_entries(),+ Some("fractional".into()),+ )+ .await+ .unwrap();assert!(is_new);assert_eq!(created.info().await.unwrap().cpus, saved_cpus);@@ -4445,7 +4470,8 @@ mod tests {BoxOptions {cpus,..options.clone()- },+ }+ .into_entries(),Some("fractional".into()),).await@@ -4466,7 +4492,8 @@ mod tests {BoxOptions {cpus: Some(1.5),..options- },+ }+ .into_entries(),Some("fractional".into()),).awaitdiff --git a/src/boxlite/src/volumes/local_store.rs b/src/boxlite/src/volumes/local_store.rsindex 698f8065a..21cbfd843 100644--- a/src/boxlite/src/volumes/local_store.rs+++ b/src/boxlite/src/volumes/local_store.rs@@ -1610,10 +1610,11 @@ mod tests {..Default::default()};let local = crate::runtime::rt_impl::LocalRuntime(Arc::clone(&runtime));- let error = crate::runtime::backend::RuntimeBackend::create(&local, options, None)- .await- .err()- .expect("a duplicate name must not select an arbitrary volume");+ let error =+ crate::runtime::backend::RuntimeBackend::create(&local, options.into_entries(), None)+ .await+ .err()+ .expect("a duplicate name must not select an arbitrary volume");assert!(matches!(error, BoxliteError::MetadataError(_)), "{error:?}");}@@ -1671,9 +1672,10 @@ mod tests {..Default::default()};let local = crate::runtime::rt_impl::LocalRuntime(Arc::clone(&runtime));- let box_handle = crate::runtime::backend::RuntimeBackend::create(&local, options, None)- .await- .expect("resolve a healthy volume by name");+ let box_handle =+ crate::runtime::backend::RuntimeBackend::create(&local, options.into_entries(), None)+ .await+ .expect("resolve a healthy volume by name");let (config, _) = runtime.box_manager.box_by_id(box_handle.id())