Skip to content

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

feat(infra): deploy isolated Secret Server roles on GCP (#3156)

Jiaqiang Wong93fe72e0cad9
diff --git a/.github/actions/mbuild/action.yml b/.github/actions/mbuild/action.yml
index 5dbf6d950..c548b5389 100644
--- a/.github/actions/mbuild/action.yml
+++ b/.github/actions/mbuild/action.yml
@@ -1,6 +1,9 @@
name: Build or promote stage images
description: Run mbuild in the caller target Environment
inputs:
+ artifact:
+ description: Publish one declared artifact, or all when empty
+ default: ''
command:
description: Image operation publish or promote
required: true
@@ -178,13 +181,17 @@ runs:
- name: Build and upload
if: inputs.command == 'publish'
working-directory: apps/infra
+ env:
+ ARTIFACT: ${{ inputs.artifact }}
shell: bash
run: |
set -Eeuo pipefail
+ artifact_args=(--tag "$IMAGE_TAG" --stage "$TARGET_STAGE")
+ if [[ -n "${ARTIFACT:-}" ]]; then artifact_args+=(--artifact "$ARTIFACT"); fi
# Audit failures (65) and image scan refusals (78) stop immediately.
# Other publication failures retain retries for transient errors.
for attempt in 1 2 3; do
- npm run --silent mbuild publish -- --tag "$IMAGE_TAG" --stage "$TARGET_STAGE" && exit 0
+ npm run --silent mbuild publish -- "${artifact_args[@]}" && exit 0
status=$?
if [ "$status" -eq 65 ]; then
echo "::error title=publish::$IMAGE_TAG failed the dependency audit; details are above"
@@ -226,6 +233,8 @@ runs:
# What was published, so a deploy can be dispatched against exactly these
# bytes without reading the log above.
- name: Report what was published
+ env:
+ ARTIFACTS: ${{ inputs.command == 'publish' && inputs.artifact || steps.config.outputs.artifacts }}
shell: bash
run: |
set -Eeuo pipefail
@@ -238,5 +247,5 @@ runs:
echo "| stage | \`$TARGET_STAGE\` |"
echo "| registry | \`${{ steps.config.outputs.kind }}\` in \`${{ steps.config.outputs.region }}\` |"
echo "| repository | \`${{ steps.config.outputs.repository }}\` |"
- echo "| artifacts | \`${{ steps.config.outputs.artifacts }}\` |"
+ echo "| artifacts | \`$ARTIFACTS\` |"
} >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/actions/mdeploy/action.yml b/.github/actions/mdeploy/action.yml
index 5d023b1a2..eb98a50c3 100644
--- a/.github/actions/mdeploy/action.yml
+++ b/.github/actions/mdeploy/action.yml
@@ -13,6 +13,9 @@ inputs:
version:
description: Stable release selector or empty for a commit
default: ''
+ runner-build-version:
+ description: Workspace version of the commit used to build the staged Runner
+ default: ''
registry-digests:
description: Verified release manifest and image digests from the release resolver
required: false
@@ -73,6 +76,7 @@ runs:
VERSION: ${{ inputs.version }}
SHA: ${{ inputs.sha }}
COMPONENTS: ${{ inputs.components }}
+ RUNNER_BUILD_VERSION: ${{ inputs.runner-build-version }}
run: |
set -Eeuo pipefail
if [[ -n "$RELEASE_PINS" ]]; then
@@ -96,6 +100,7 @@ runs:
printf 'RUNNER_ARTIFACT_SOURCE=%s\n' "$source"
if [ "$source" = 'build' ]; then
printf 'RUNNER_ARTIFACT_REF=%s\n' "$SHA"
+ printf 'VERSION=%s\n' "${RUNNER_BUILD_VERSION:?Missing staged Runner version}"
elif [ -n "$VERSION" ]; then
# `VERSION` is the selector `stack/runner-binary.ts` honours; it
# strips the leading v itself. Left unset on a commit rollout that
@@ -213,8 +218,13 @@ runs:
working-directory: apps/infra
env:
STAGE: ${{ inputs.stage }}
+ API_ONLY: ${{ inputs.components == 'api' }}
shell: bash
- run: npm run --silent mbuild verify -- --tag "$BOXLITE_IMAGE_TAG" --stage "$STAGE"
+ run: |
+ set -Eeuo pipefail
+ artifact_args=(--tag "$BOXLITE_IMAGE_TAG" --stage "$STAGE")
+ if [[ "${API_ONLY:-false}" == true ]]; then artifact_args+=(--artifact api); fi
+ npm run --silent mbuild verify -- "${artifact_args[@]}"
# ----------------------------------------------------------- 5/5
# Read through mstage's own loader, out of the declaration setup-infra
diff --git a/.github/workflows/mdeploy-all.yml b/.github/workflows/mdeploy-all.yml
index 51a36b55b..33ab30cb3 100644
--- a/.github/workflows/mdeploy-all.yml
+++ b/.github/workflows/mdeploy-all.yml
@@ -150,6 +150,8 @@ jobs:
runs-on: ubuntu-latest
outputs:
sha: ${{ steps.tag.outputs.sha }}
+ infra_sha: ${{ steps.infra.outputs.sha }}
+ runner_build_version: ${{ steps.runner-version.outputs.version }}
version: ${{ steps.classify.outputs.version }}
image_tag: ${{ steps.tag.outputs.image }}
candidate_id: ${{ steps.upload.outputs.artifact-id }}
@@ -260,7 +262,7 @@ jobs:
PR: ${{ steps.classify.outputs.pr }}
run: |
set -Eeuo pipefail
- fields=state,headRefOid,isCrossRepository,mergeable,potentialMergeCommit
+ fields=state,headRefOid,baseRefName,isCrossRepository,mergeable,potentialMergeCommit
if ! pr_json="$(gh pr view "$PR" --repo "$GITHUB_REPOSITORY" --json "$fields" 2>&1)"; then
echo "::error title=pull request::no pull request #$PR in this repository ($pr_json)"
exit 1
@@ -310,6 +312,8 @@ jobs:
# says what that is and is not worth.
fork="$(jq -r '.isCrossRepository' <<<"$pr_json")"
head="$(jq -r '.headRefOid' <<<"$pr_json")"
+ printf 'head=%s\n' "$head" >> "$GITHUB_OUTPUT"
+ printf 'base=%s\n' "$(jq -r '.baseRefName' <<<"$pr_json")" >> "$GITHUB_OUTPUT"
echo "#$PR ($([ "$fork" = 'true' ] && echo fork || echo same-repo)) head is $head; deploying merge $sha"
printf 'sha=%s\n' "$sha" >> "$GITHUB_OUTPUT"
@@ -352,6 +356,59 @@ jobs:
esac
fi
+ # A PR merge commit can be absent from the dispatch branch's history.
+ - name: Read the resolved PR source
+ if: steps.pr.outputs.sha && (inputs.stage == 'stage' || inputs.components != 'api')
+ uses: actions/checkout@v5
+ with:
+ ref: ${{ steps.pr.outputs.sha }}
+ path: .deploy-candidate
+ sparse-checkout: apps/api/src
+ persist-credentials: false
+
+ - name: Read the staged Runner archive version
+ id: runner-version
+ if: steps.classify.outputs.version == '' && inputs.components != 'api'
+ working-directory: ${{ steps.pr.outputs.sha && '.deploy-candidate' || '.' }}
+ env:
+ SHA: ${{ steps.tag.outputs.sha }}
+ shell: bash
+ run: |
+ set -Eeuo pipefail
+ version=$(git show "$SHA:Cargo.toml" | python3 -I -c 'import sys, tomllib; print(tomllib.load(sys.stdin.buffer)["workspace"]["package"]["version"])')
+ [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "Invalid Runner build version" >&2; exit 1; }
+ printf 'version=%s\n' "$version" >> "$GITHUB_OUTPUT"
+
+ - name: Select the infrastructure checkout
+ id: infra
+ working-directory: ${{ steps.pr.outputs.sha && inputs.stage == 'stage' && '.deploy-candidate' || '.' }}
+ env:
+ STAGE: ${{ inputs.stage }}
+ COMPONENTS: ${{ inputs.components }}
+ REF: ${{ inputs.ref }}
+ CANDIDATE: ${{ steps.tag.outputs.sha }}
+ PR_HEAD: ${{ steps.pr.outputs.head }}
+ PR_BASE: ${{ steps.pr.outputs.base }}
+ shell: bash
+ run: |
+ set -Eeuo pipefail
+ sha="$GITHUB_SHA"
+ # A writer must select the exact PR head as the upstream workflow ref.
+ # Scoped rollbacks use the current worker selector and Runner enrollment policy.
+ if [[ "$STAGE" == dev && "$PR_HEAD" == "$GITHUB_SHA" && "$PR_BASE" == main ]]; then
+ sha="$CANDIDATE"
+ elif [[ "$STAGE" == stage && "$COMPONENTS" == api ]]; then
+ # Both services run this image. Inspect the resolved source for every ref spelling.
+ if ! git grep -qw CLOUD_APP_PROCESS_ROLE "$CANDIDATE" -- ':(glob)apps/api/src/**/*.ts' ':(exclude,glob)**/*.spec.ts' ||
+ ! git grep -qw CloudAppWorker "$CANDIDATE" -- ':(glob)apps/api/src/**/*.module.ts'; then
+ echo "::error title=API rollback::${REF:-$CANDIDATE} lacks CloudAppWorker support required for a stage API-only deployment"
+ exit 1
+ fi
+ elif [[ "$STAGE" == stage && "$COMPONENTS" == api+runner && "$REF" == v* ]]; then
+ sha="$CANDIDATE"
+ fi
+ printf 'sha=%s\n' "$sha" >> "$GITHUB_OUTPUT"
+
- name: Validate release caller and published commit
if: github.workflow_ref != format('{0}/.github/workflows/mdeploy-all.yml@{1}', github.repository, github.ref)
env:
@@ -501,6 +558,7 @@ jobs:
- *verify-dev-acceptance
- uses: actions/checkout@v5
with:
+ ref: ${{ needs.resolve.outputs.infra_sha }}
persist-credentials: false
- uses: ./.github/actions/setup-infra
with:
@@ -553,6 +611,7 @@ jobs:
LINE: ${{ needs.resolve.outputs.line }}
STAGE: ${{ inputs.stage }}
COMPONENTS: ${{ matrix.component == 'release' && inputs.components || matrix.component }}
+ API_ONLY: ${{ inputs.components == 'api' }}
GHCR_REPOSITORY: ${{ github.repository }}
run: |
set -Eeuo pipefail
@@ -565,7 +624,9 @@ jobs:
if [ -n "$VERSION" ]; then
api=release-import
else
- npm run --silent mbuild verify -- --tag "$IMAGE_TAG" --stage "$STAGE" || held=$?
+ artifact_args=(--tag "$IMAGE_TAG" --stage "$STAGE")
+ if [[ "${API_ONLY:-false}" == true ]]; then artifact_args+=(--artifact api); fi
+ npm run --silent mbuild verify -- "${artifact_args[@]}" || held=$?
if [ "$held" -eq 0 ]; then
echo "$STAGE already holds the images for $IMAGE_TAG"
elif [ "$held" -ne 66 ]; then
@@ -625,6 +686,7 @@ jobs:
gcp-workload-identity-provider: ${{ vars.GCP_WORKLOAD_IDENTITY_PROVIDER }}
gcp-image-publisher: ${{ vars.GCP_IMAGE_PUBLISHER }}
command: publish
+ artifact: ${{ inputs.components == 'api' && 'api' || '' }}
tag: ${{ needs.resolve.outputs.sha }}
stage: ${{ inputs.stage }}
@@ -700,6 +762,7 @@ jobs:
steps:
- uses: actions/checkout@v5
with:
+ ref: ${{ needs.resolve.outputs.infra_sha }}
persist-credentials: false
fetch-depth: 0
- uses: ./.github/actions/mdeploy
@@ -713,6 +776,7 @@ jobs:
stage: ${{ inputs.stage }}
sha: ${{ needs.resolve.outputs.sha }}
version: ${{ needs.resolve.outputs.version }}
+ runner-build-version: ${{ needs.resolve.outputs.runner_build_version }}
image-tag: ${{ needs.resolve.outputs.image_tag }}
registry-digests: ${{ needs.resolve.outputs.registry_digests }}
line: ${{ needs.resolve.outputs.line }}
diff --git a/apps/infra/docs/gcp/deployment.md b/apps/infra/docs/gcp/deployment.md
index a63b80724..35c8e57b8 100644
--- a/apps/infra/docs/gcp/deployment.md
+++ b/apps/infra/docs/gcp/deployment.md
@@ -68,7 +68,7 @@ mdeploy uses Pulumi with GCS state. API/dashboard, collector and registry proxy
the proxy runs on GKE Autopilot, and runners use Compute Engine; see [architecture](architecture.md).
Cloudflare credentials come from the encrypted `deploy` group.
-The API, collector and registry proxy set Service metadata `labels.stage`; the GKE Proxy cluster sets `resourceLabels.stage`.
+The API, collector, registry proxy and both Secret Server services set Service metadata `labels.stage`; the GKE Proxy cluster sets `resourceLabels.stage`.
Both use the deployed stage, for example `dev`, so Backoffice can select matching resources.
Apply these labels before enabling strict inventory filtering; unlabeled resources remain excluded until deployment and Cloud Asset indexing complete.
diff --git a/apps/infra/docs/gcp/runners.md b/apps/infra/docs/gcp/runners.md
index 014fb4287..79d4855fb 100644
--- a/apps/infra/docs/gcp/runners.md
+++ b/apps/infra/docs/gcp/runners.md
@@ -56,6 +56,12 @@ revision. A failed update, missing report or stale revision stops progression. T
running, and runner labels must be unique after normalization. The command refuses `--host`;
the next mdeploy reasserts the checkout's policy target. Both paths verify binary checksums and readiness.
Already-converged hosts need no restart. Release downgrades require the explicit `--allow-downgrade` update command.
+The installer records the version and SHA-256 of the installed executable.
+If a healthy enrolled Runner has a missing or stale record, OS Config verifies the pinned OCI release or checksummed
+commit archive and compares its executable with the serving systemd process before writing the record.
+This refresh leaves the process running. If an enrolled Runner cannot serve its health endpoint,
+OS Config can install a strictly newer release when the recorded hash matches the binary on disk. A host with missing or stale
+installation evidence must recover its health endpoint or receive an explicit operator update.
IAP/OS Login remains available for authorized administration, but normal updates do not require per-user SSH.
For an existing deployment, run mdeploy once to narrow the original assignment to the first runner and
diff --git a/apps/infra/docs/release.md b/apps/infra/docs/release.md
index 874bb18c7..1f5d6309c 100644
--- a/apps/infra/docs/release.md
+++ b/apps/infra/docs/release.md
@@ -24,6 +24,8 @@ The run creates the draft or selects the existing draft for that tag. Configure
| Publish | A passing dev E2E or a recorded [waiver](#review-a-failed-dev-e2e) opens prod approval immediately. In parallel, publication waits for the complete distribution and Go tests, compares the tested client bytes against the draft and records the accepted candidate. The top-level PyPI and npm jobs publish the accepted packages. |
| Release and prod | When those publishers succeed, the workflow marks the draft public. Rust crates can then publish, and the Go job verifies the public C SDK downloads before tagging the tested commit. Approved prod deployment uses the same GHCR digests and can finish while the release is still a draft. |
+Releases whose artifact declaration includes `secret-server` publish its image to GHCR. GCP dev, stage and prod deploy it alongside the API.
+
The C SDK and Runner workflows each load CI configuration and validate the build commit in one preparation job. A regular release skips the lookup for a previous acceptance receipt. Once its own attachments succeed, npm and PyPI can start. Finalization requires both to succeed.
The Runner package at `ghcr.io/boxlite-ai/boxlite/runner` must allow anonymous pulls from hosts. First boot and in-place upgrade verify the OCI manifest against the release tag, source commit and archive digest before extracting the binary. Dev and prod receive those pins from the candidate. A version-only manual rollout reads the same pins from the published `release-candidate.json`.
diff --git a/apps/infra/mbuild/README.md b/apps/infra/mbuild/README.md
index a4819e14c..10a030e9f 100644
--- a/apps/infra/mbuild/README.md
+++ b/apps/infra/mbuild/README.md
@@ -7,7 +7,10 @@ mbuild publishes, verifies, and promotes the container artifacts declared by mst
[Infrastructure index](../README.md) · [Deployment](../docs/deployment.md) · [Configuration](../docs/configuration.md)
Run from `apps/infra`. Bootstrap the registry and sign in before commands that contact it.
-The four declared artifacts are `api` (including dashboard), `proxy`, `otel-collector`, and `registry-proxy`.
+The image declaration includes `api` (with dashboard), `proxy`, `otel-collector`, `registry-proxy`, and `secret-server`.
+Release publishing builds the declared images. Deployment verification and release import honor an artifact's optional
+`deployStages` list and `deployCloud` provider. GCP dev, stage and prod require the Secret Server image. For a full GCP production rollout or
+rollback, select a published release that includes this image.
Runner binaries use the separate [runner commands](../docs/runners.md).
## Commands
@@ -57,7 +60,9 @@ The address is `ghcr.io/<owner>/<repository>/<artifact>:vX.Y.Z-<full-sha>`.
Artifact names and tags match Artifact Registry's layout; GHCR has no stage suffix.
Set `GHCR_USERNAME` and `GHCR_TOKEN`, or use `GITHUB_ACTOR` and `GH_TOKEN` in Actions.
Publishing needs package write access; verification/import needs package read access.
-`publish` and `verify` with `--ghcr` read the artifact declaration without a cloud stage file.
+GHCR publication and GHCR verification without a target stage read the artifact declaration without a cloud stage file.
+For `verify --ghcr --stage <name>`, declare that stage in the mstage config. Its cloud and name
+select the deployment images to verify in GHCR.
For publication, use `MSTAGE_ENV_CONFIG` to select the release source's declaration and build context.
`import-release` imports and verifies the artifacts required by its current declaration;
an older release lacking a required artifact fails this import.
@@ -81,6 +86,7 @@ Pending or missing discovery waits up to the configured timeout; failed or unsup
Confirmed missing manifests exit `66`; authentication, transport and other registry errors fail separately.
Stage-to-stage promotion copies existing image bytes within one cloud registry kind. Cross-cloud promotion is refused.
+When no artifact is specified, the destination stage's cloud and name determine which images to promote.
The caller needs source read and destination write access; `promoteFrom` lets bootstrap prepare
those permissions. On AWS, the current CLI uses one resolved account for both registry addresses.
diff --git a/apps/infra/mbuild/bin/mbuild.ts b/apps/infra/mbuild/bin/mbuild.ts
index 4117daad1..bb372d0d5 100755
--- a/apps/infra/mbuild/bin/mbuild.ts
+++ b/apps/infra/mbuild/bin/mbuild.ts
@@ -18,7 +18,7 @@ import { writeFile } from 'node:fs/promises'
*/
import { loadConfig as loadStageConfig, type StageConfig } from 'mstage/config'
-import { loadArtifactConfig, loadBuildConfig, onlyArtifact, registryFor, type BuildConfig } from '../src/config.ts'
+import { deploymentArtifacts, loadArtifactConfig, loadBuildConfig, onlyArtifact, registryFor, stageIn, type BuildConfig } from '../src/config.ts'
import { assertTag, ghcrRegistryFor, releaseImageDigests, releaseTagFor, resolveRegistry } from '../src/address.ts'
import { assertPromotable, coordinatesOf, type Coordinates } from '../src/coordinates.ts'
import {
@@ -101,9 +101,10 @@ const required = (argv: string[], name: string): string => {
* stage hold this commit" is a question about all of them. Named, it narrows
* to that one, which is what lets a workflow give each artifact its own job.
*/
-const narrowed = (config: BuildConfig, argv: string[]): BuildConfig => {
+const narrowed = (config: BuildConfig, argv: string[], deployStage?: string): BuildConfig => {
const artifact = option(argv, 'artifact')
- return artifact === undefined ? config : onlyArtifact(config, artifact)
+ if (artifact !== undefined) return onlyArtifact(config, artifact)
+ return deployStage ? deploymentArtifacts(config, deployStage) : config
}
/**
@@ -178,16 +179,18 @@ const coordinates = (config: BuildConfig, stage: string): Promise<Coordinates> =
const main = async (): Promise<number> => {
const [command, ...argv] = process.argv.slice(2)
const ghcr = option(argv, 'ghcr')
- const config = ghcr !== undefined && command !== 'import-release' ? loadArtifactConfig() : loadBuildConfig()
+ const verifyForStage = command === 'verify' && argv.some((arg) => arg === '--stage' || arg.startsWith('--stage='))
+ const config = ghcr !== undefined && command !== 'import-release' && !verifyForStage
+ ? loadArtifactConfig() : loadBuildConfig()
if (ghcr !== undefined) {
if (!['publish', 'verify', 'import-release'].includes(command ?? '')) throw new Error('--ghcr requires publish, verify or import-release')
if (!option(argv, 'version') || !/^[0-9a-f]{40}$/.test(required(argv, 'tag'))) throw new Error('--ghcr requires --version and a full commit SHA')
const registry = ghcrRegistryFor(ghcr)
const tag = tagOf(argv)
- const selected = narrowed(config, argv)
if (command === 'import-release') {
const stage = required(argv, 'stage')
+ const selected = narrowed(config, argv, stage)
const target = resolveRegistry({ config, stage, region: regionOf(stage), ...(await coordinates(config, stage)) })
const pins = process.env.BOXLITE_RELEASE_DIGESTS
const digests = pins ? releaseImageDigests(pins, tag) : undefined
@@ -195,7 +198,9 @@ const main = async (): Promise<number> => {
console.log(`${outcome.artifact}=${outcome.address}`)
}
} else {
- const options = { config: selected, stage: 'ghcr', registry, tag, run, log }
+ const stage = verifyForStage ? required(argv, 'stage') : undefined
+ if (stage !== undefined) stageIn(config, stage)
+ const options = { config: narrowed(config, argv, stage), stage: 'ghcr', registry, tag, run, log }
const outcomes = command === 'publish'
? await publish({ ...options, replace: argv.includes('--replace') })
: await verifyPublished(options)
@@ -247,7 +252,7 @@ const main = async (): Promise<number> => {
region: regionOf(stage),
...(await coordinates(config, stage)),
})
- for (const { artifact, address } of await verifyPublished({ config: narrowed(config, argv), stage, registry, tag, run })) {
+ for (const { artifact, address } of await verifyPublished({ config: narrowed(config, argv, stage), stage, registry, tag, run })) {
console.log(`${artifact}=${address}`)
}
return 0
@@ -266,7 +271,7 @@ const main = async (): Promise<number> => {
// reusing the source's would push the promoted image at the wrong one while
// reporting the right name.
const outcomes = await promote({
- config: narrowed(config, argv),
+ config: narrowed(config, argv, toStage),
tag,
from: {
stage: fromStage,
diff --git a/apps/infra/mbuild/src/address.ts b/apps/infra/mbuild/src/address.ts
index d4379d7ee..702621296 100644
--- a/apps/infra/mbuild/src/address.ts
+++ b/apps/infra/mbuild/src/address.ts
@@ -199,7 +199,8 @@ export const addressesFor = ({
Object.keys(config.artifacts).map((artifact) => {
const address = addressFor({ config, registry, artifact, tag })
if (!digests) return [artifact, address]
- const digest = digests[artifact] ?? ''
+ const digest = digests[artifact]
+ if (digest === undefined) throw new ImageAddressError(`Release manifest is missing a digest for ${artifact}`)
digestTag(digest)
return [artifact, address.slice(0, address.lastIndexOf(':')) + '@' + digest]
}),
diff --git a/apps/infra/mbuild/src/config.ts b/apps/infra/mbuild/src/config.ts
index 122ef0640..adc8fc108 100644
--- a/apps/infra/mbuild/src/config.ts
+++ b/apps/infra/mbuild/src/config.ts
@@ -70,6 +70,9 @@ export type ArtifactConfig = {
dockerfile: string
/** Build context, repository-relative. Usually the root, for a workspace. */
context: string
+ /** Which deployments require the image. Release publication builds every declared artifact. */
+ deployCloud?: StageConfig['home']
+ deployStages?: string[]
}
/**
@@ -249,10 +252,25 @@ const parseArtifacts = (raw: unknown, where: string): Record<string, ArtifactCon
throw new BuildConfigError(`${where}: artifact "${name}" must match ${ARTIFACT_NAME.source}`)
}
const artifact = assertObject(block[name], `${where}.${name}`)
- assertKeys(artifact, ['dockerfile', 'context'], `${where}.${name}`)
+ assertKeys(artifact, ['dockerfile', 'context', 'deployCloud', 'deployStages'], `${where}.${name}`, ['deployCloud', 'deployStages'])
+ const cloud = artifact.deployCloud
+ if (cloud !== undefined && cloud !== 'aws' && cloud !== 'gcp') {
+ throw new BuildConfigError(`${where}.${name}.deployCloud must be aws or gcp`)
+ }
+ const stages = artifact.deployStages
+ if (
+ stages !== undefined &&
+ (!Array.isArray(stages) ||
+ !stages.length ||
+ stages.some((stage) => typeof stage !== 'string' || !ARTIFACT_NAME.test(stage)))
+ ) {
+ throw new BuildConfigError(`${where}.${name}.deployStages must contain stage names`)
+ }
parsed[name] = {
dockerfile: assertContainedPath(artifact.dockerfile, `${where}.${name}.dockerfile`),
context: assertContainedPath(artifact.context, `${where}.${name}.context`),
+ ...(cloud && { deployCloud: cloud }),
+ ...(stages && { deployStages: stages }),
}
}
return parsed
@@ -506,3 +524,11 @@ export const onlyArtifact = (config: BuildConfig, artifact: string): BuildConfig
}
return { ...config, artifacts: { [artifact]: config.artifacts[artifact]! } }
}
+
+export function deploymentArtifacts(config: BuildConfig, stage: string): BuildConfig {
+ const artifacts = Object.entries(config.artifacts).filter(
+ ([, artifact]) => (!artifact.deployStages || artifact.deployStages.includes(stage)) &&
+ (!artifact.deployCloud || config.stages[stage]?.home === artifact.deployCloud),
+ )
+ return { ...config, artifacts: Object.fromEntries(artifacts) }
+}
diff --git a/apps/infra/mbuild/test/address.test.ts b/apps/infra/mbuild/test/address.test.ts
index 5eaf73a0d..596ffe25d 100644
--- a/apps/infra/mbuild/test/address.test.ts
+++ b/apps/infra/mbuild/test/address.test.ts
@@ -13,7 +13,30 @@ import {
releaseImageDigests,
resolveRegistry,
} from '../src/address.ts'
-import { BuildConfigError, onlyArtifact, parseBuildConfig, registryFor } from '../src/config.ts'
+import {
+ BuildConfigError,
+ deploymentArtifacts,
+ onlyArtifact,
+ parseBuildConfig,
+ registryFor,
+} from '../src/config.ts'
+
+test('the deployment image set requires Secret Server in each deployment stage', () => {
+ const base = readFileSync(new URL('../../mstage.env.json', import.meta.url), 'utf8')
+ const stages = readFileSync(new URL('../../.mstage.config.example.json', import.meta.url), 'utf8')
+ const aws = parseBuildConfig({ base, stages, basePath: '/repo/mstage.env.json', stagePath: '/repo/stages.json' })
+ for (const stage of ['dev', 'prod']) {
+ assert.equal(deploymentArtifacts(aws, stage).artifacts['secret-server'], undefined, 'AWS ' + stage)
+ }
+ const config = { ...aws, stages: Object.fromEntries(['dev', 'stage', 'prod'].map(stage => [stage, aws.stages.dev2!])) }
+ for (const stage of ['dev', 'stage', 'prod']) {
+ assert.equal(
+ deploymentArtifacts(config, stage).artifacts['secret-server']?.dockerfile,
+ 'apps/secret-server/Dockerfile',
+ )
+ }
+ assert.equal(deploymentArtifacts(config, 'preview').artifacts['secret-server'], undefined)
+})
const SCAN = { blockOn: ['CRITICAL', 'HIGH'], timeoutSeconds: 300 }
diff --git a/apps/infra/mbuild/test/ghcr-cli.test.ts b/apps/infra/mbuild/test/ghcr-cli.test.ts
index 1d1ef8a30..30b6334df 100644
--- a/apps/infra/mbuild/test/ghcr-cli.test.ts
+++ b/apps/infra/mbuild/test/ghcr-cli.test.ts
@@ -15,20 +15,45 @@ const digest = `sha256:${createHash('sha256').update(manifest).digest('hex')}`
const cli = fileURLToPath(new URL('../bin/mbuild.ts', import.meta.url))
const loader = fileURLToPath(new URL('../../node_modules/tsx/dist/loader.mjs', import.meta.url))
-const fixture = (t: TestContext, cloud = false) => {
+const fixture = (t: TestContext, cloud = false, prod?: 'aws' | 'gcp' | 'undeclared') => {
const directory = mkdtempSync(join(tmpdir(), 'mbuild-ghcr-cli-'))
t.after(() => rmSync(directory, { recursive: true, force: true }))
const script = (name: string, body: string) => writeFileSync(join(directory, name), `#!/bin/bash\nset -eu\n${body}\n`, { mode: 0o755 })
- writeFileSync(join(directory, 'mstage.env.json'), JSON.stringify({ app: 'cli-test', root: '.', artifacts: { api: { dockerfile: 'Dockerfile', context: '.' } } }))
+ const image = { dockerfile: 'Dockerfile', context: '.' }
+ const artifacts = prod === undefined ? { api: image } : {
+ api: image, proxy: image, 'registry-proxy': image, 'otel-collector': image,
+ 'secret-server': { ...image, deployStages: ['prod'], deployCloud: 'gcp' },
+ }
+ writeFileSync(join(directory, 'mstage.env.json'), JSON.stringify({ app: 'cli-test', root: '.', artifacts }))
+ const gcp = { home: 'gcp', region: 'us-east1', project: 'project', registry: { kind: 'artifact-registry', repository: 'images', immutableTags: true, scanOnPush: true }, scan: { blockOn: 'DISABLED' } }
+ const aws = { home: 'aws', region: 'us-east-1', registry: { ...gcp.registry, kind: 'ecr' }, scan: gcp.scan }
writeFileSync(join(directory, '.mstage.config.json'), JSON.stringify({ stages: {
- dev: { home: 'gcp', region: 'us-east1', project: 'project', registry: { kind: 'artifact-registry', repository: 'images', immutableTags: true, scanOnPush: true }, scan: { blockOn: 'DISABLED' } },
+ dev: prod === 'aws' ? { ...aws, registry: { ...aws.registry, repository: 'images-dev' } } : gcp,
+ ...(prod === 'aws'
+ ? { prod: { ...aws, registry: { ...aws.registry, repository: 'images-prod' } } }
+ : prod === 'gcp' ? { prod: gcp } : {}),
} }))
- script('curl', `if [[ "$*" == *'/token?'* ]]; then body='{"token":"bearer-token"}'; type='application/json'; else body='${manifest}'; type='${mediaType}'; fi
-printf '%s\\n200' "$body"
+ script('curl', `status=200
+case "$*" in
+ *'/token?'*) body='{"token":"bearer-token"}'; type='application/json' ;;
+ *'/secret-server/manifests/'*) status=404; body='{"errors":[{"code":"MANIFEST_UNKNOWN"}]}'; type='application/json' ;;
+ *) body='${manifest}'; type='${mediaType}' ;;
+esac
+printf '%s\\n%s' "$body" "$status"
if [[ "$*" == *'%{content_type}'* ]]; then printf '\\n%s' "$type"; fi`)
script('gcloud', `if [[ "$*" == *'repositories describe'* ]]; then printf True;
elif [[ "$*" == *'--format=json'* ]]; then printf '%s' '${JSON.stringify([{ version: digest, tags: [tag] }])}';
elif [[ "$*" == *'images list'* ]]; then printf '%s' '${digest}'; fi`)
+ script('aws', `case "$1 $2" in
+ "sts get-caller-identity") echo 123456789012 ;;
+ "ecr describe-images")
+ if [[ "$*" == *images-prod* || "$*" == *-secret-server* ]]; then
+ echo ImageNotFoundException >&2
+ exit 254
+ fi ;;
+ "ecr describe-repositories"|"ecr get-login-password") ;;
+ *) echo "unexpected mock AWS operation: $1 $2" >&2; exit 99 ;;
+esac`)
script('docker', 'exit 0')
const env = { ...process.env, PATH: `${directory}:${process.env.PATH}`, MSTAGE_ENV_CONFIG: join(directory, 'mstage.env.json'), MSTAGE_CONFIG: join(directory, cloud ? '.mstage.config.json' : 'missing-stage-config.json'),
GHCR_USERNAME: 'actor', GHCR_TOKEN: 'test-token', GITHUB_ACTIONS: 'true', GITHUB_REPOSITORY: 'boxlite-ai/boxlite',
@@ -57,3 +82,34 @@ test('GHCR CLI rejects unsupported operations, incomplete releases and unknown a
assert.match(result.stderr, expected)
}
})
+
+for (const prod of ['aws', 'gcp', 'undeclared'] as const) test(`GHCR verify uses the declared prod stage (${prod})`, (t) => {
+ const run = fixture(t, true, prod)
+ const args = ['verify', '--ghcr', 'boxlite-ai/boxlite', '--tag', sha, '--version', 'v1.2.3', '--stage', 'prod']
+ const result = run(args)
+ if (prod === 'aws') {
+ assert.equal(result.status, 0, result.stderr)
+ assert.deepEqual(result.stdout.trim().split('\n').map((line) => line.split('=')[0]).sort(),
+ ['api', 'otel-collector', 'proxy', 'registry-proxy'])
+ } else if (prod === 'gcp') {
+ assert.equal(result.status, 66, result.stderr)
+ assert.match(result.stderr, /secret-server/)
+ } else {
+ for (const check of [result, run([...args, '--artifact', 'api'])]) {
+ assert.equal(check.status, 1, check.stdout + check.stderr)
+ assert.match(check.stderr, /declares no stage "prod"\. Declared: dev/)
+ }
+ }
+})
+
+test('AWS promotion copies the four images required by prod', (t) => {
+ const run = fixture(t, true, 'aws')
+ const verified = run(['verify', '--stage', 'dev', '--tag', sha])
+ assert.equal(verified.status, 0, verified.stderr)
+
+ const result = run(['promote', '--from', 'dev', '--to', 'prod', '--tag', sha])
+ assert.equal(result.status, 0, result.stderr)
+ const addresses = result.stdout.trim().split('\n').map((line) => line.split('='))
+ assert.deepEqual(addresses.map(([name]) => name).sort(), ['api', 'otel-collector', 'proxy', 'registry-proxy'])
+ for (const [name, address] of addresses) assert.match(address!, new RegExp(`/images-prod:${sha}-${name}$`))
+})
diff --git a/apps/infra/mdeploy/README.md b/apps/infra/mdeploy/README.md
index 3150d2f9d..d930425cb 100644
--- a/apps/infra/mdeploy/README.md
+++ b/apps/infra/mdeploy/README.md
@@ -165,9 +165,9 @@ Each stage declares `home`; that field selects credentials, store backend, engin
There is no repository-wide cloud default. Read the separate [GCP](../docs/gcp/architecture.md) or
[AWS](../docs/aws/architecture.md) architecture and operations guides for resource mappings and network paths.
-For the GCP `stage` environment, API, Collector and Registry Proxy declare the Service-level label `stage=stage`.
+For the GCP `stage` environment, the API, Collector, Registry Proxy and both Secret Server services declare the service-level label `stage=stage`.
Backoffice uses this label to scope discovery within the shared dev project; labels do not provide IAM isolation.
-These declarations leave revision labels and all other environments unchanged. Service discovery requires deployment and Cloud Asset indexing.
+Service discovery requires deployment and Cloud Asset indexing.
GCP workload service accounts keep the `<appShort>-<stage>-<artifact>-run` identity format and the 30-character limit.
For `stage`, two artifact segments use shorter names:
@@ -226,12 +226,18 @@ For a configuration-only change, select its component and reuse the deployed art
Pulumi still evaluates the full inline program and validates its inputs, using recorded outputs for untargeted dependencies.
New API secret references and a Runner release-to-build transition include their required read grants, even when absent from old state.
Shared infrastructure changes require a full deployment; scoped updates skip the unrelated DNS/certificate preflight.
-Runner-only runs skip container-image verification; API-only release runs require a published release but not Runner attachments.
+On GCP, a Runner-only release plan validates the Runner manifest and archive digests and targets the Runner OS policies and artifact access grant.
+It can use a release that predates the Secret Server image. API and full GCP release plans require a digest for each image deployed in the selected stage.
+For example, `dev2` uses four images. GCP `dev`, `stage` and `prod` also require the Secret Server digest.
+On the dev/prod release path, API-only runs require a published release and can proceed without Runner attachments.
+For a commit or stage tag, API-only runs verify and, when necessary, build the single API image shared by the API and CloudAppWorker.
+For an intentional host downgrade, use `runner:update --allow-downgrade` from a checkout that understands the deployed policy.
Local provider/target tests do not prove live Cloud Run health or OS Config host compliance.
A commit or open PR merge commit is accepted for `dev` and `stage`; both may use candidate workflow branches.
`prod` requires a published release; release dispatches run from `main`.
Stage resolves stable tags to their commits and uses SHA-tagged images and a commit Runner build.
+The Runner archive version comes from the same commit as the build, including when the deployment workflow runs from another branch.
Dev/prod release deployments import the existing version-qualified images from GHCR.
Commit images and Runner artifacts each have a parallel plan/build matrix leg with isolated checkout and cloud credentials.
Review both pending preparation jobs as one target Environment batch; commit deployment requires a separate approval.
@@ -301,3 +307,90 @@ so moving the helper preserves its check against the shared store's allowlist.
Run `make test:apps:infra` from the repository root for tooling checks. A passing local test or
preview is not live rollout proof; follow the [deployment verification](../docs/deployment.md#verify-the-result).
+## GCP Secret Server
+
+A full GCP `dev`, `stage` or `prod` deploy creates `boxlite_secrets` on the existing Cloud SQL instance and connects through
+the mounted Unix socket as `boxlite`. The database and generated 32-byte master key have Pulumi replacement protection.
+Write and fetch revisions receive pinned Secret Manager versions for `DATABASE_URL` and `SECRET_MASTER_KEY_BASE64`.
+The shared PostgreSQL account retains access to both databases. Each stage generates its own key. Both production
+roles run with `ENVIRONMENT=production` and Google authentication. They use the same `SECRET_MASTER_KEY_ID` and
+numbered `SECRET_MASTER_KEY_BASE64` version across revisions. Restore the database with the matching key ID and material.
+
+| Cloud Run role | Ingress and invoker | Application checks |
+| --- | --- | --- |
+| `write` | Internal, API service account | Google token audience and API email allowlist |
+| `fetch` | Internal, Runner service account | Full instance identity, project, service account and registered machine ID |
+
+In dev, stage and prod, Cloud Run keeps one instance of each service warm even when idle.
+Write and fetch scale independently with CPU usage and concurrent requests. Each revision can scale up to two instances.
+
+Both Secret Server roles attach to the stage's primary private subnet using its regional resource ID
+(`projects/<project>/regions/<region>/subnetworks/<name>`). Both callers use the private `run.app` DNS zone.
+Deployment selects the Cloud Run serving URL that matches
+the role's configured Google token audience. If Cloud Run omits that address, deployment stops before distributing it.
+The API receives the write URL. On full apply, once the VMs exist and any extra Runner registrations finish,
+the deployment host waits up to five minutes for `/api/health` on the public API. For each slot it reads
+the live GCE instance ID as a decimal string by project, zone and VM name using `gcloud compute instances describe`.
+It then uses the slot's token to read the UUID from `GET /api/runners/me` on the same origin, retrying briefly
+if the default Runner is still registering.
+It verifies the registered name and v2 API version and passes the complete `gcp_iit` map to the fetch revision.
+A missing identity, repeated UUID or failed lookup stops publication. A later full apply reads the current fleet
+again, including replacement VMs and re-registered Runners. The GCE OS Config policy distributes the verified
+fetch URL and the VM IDs from the ready Fetch revision serving all traffic. If an apply stops after discovery,
+a Runner-only retry uses the registry from the last completed Fetch rollout. A replacement VM needs a full apply to enroll.
+OS Config installs the URL and the host's own ID in `/etc/boxlite/secret-fetch.env` through a systemd drop-in.
+This can run before first boot finishes and survives the boot script rewriting `runner.env` on restart.
+The startup wrapper checks the ID against GCE metadata before launching the Runner. API registration
+can complete while the host waits. OS Config applies the environment before checking the binary. Release updates
+wait for the restarted Runner to report its current version before deciding whether to replace it.
+Existing VMs keep their original boot scripts and receive the settings during the full rollout.
+When only the enrollment ID needs installing, OS Config leaves a running Runner and its Boxes in place after
+verifying the process already uses the correct fetch URL. A waiting startup wrapper or changed runtime settings
+still require service activation.
+Use a full deploy to provision or change this registry; component previews and Runner-only updates do not run identity discovery.
+Set `SECRET_SERVER_ENABLED=true` in the API group to exercise forwarding and wait for Runner OS Config convergence before the E2E test.
+
+Cloud Run sends the write and fetch service logs to Cloud Logging in dev, stage and prod.
+To enable Secret Server alerts in an environment, set `SECRET_SERVER_INCIDENT_CHANNEL` in its deploy group to
+`projects/<stage-project-id>/notificationChannels/<id>` for its incident.io webhook channel.
+Leaving it unset or empty skips the three log-based metrics and their alert policies. Removing a previously configured
+channel removes those managed resources on the next full apply. Alerts cover decryption failures, API-confirmed replays
+and high successful fetch counts.
+The default volume threshold is 100 successful requests for one Runner in five minutes, summed across revisions.
+`SECRET_SERVER_FETCH_LIMIT` overrides that count. Fetch-side metrics start receiving events when the fetch handler is deployed.
+
+### Verify a rollout
+
+1. For dev infrastructure changes, dispatch from an upstream task branch at the exact deployment PR head, targeting a PR based on `main`.
+ For stage, dispatch from `main` and select a stable tag. A full deployment uses that tag's infrastructure.
+ A scoped rollback uses the dispatch commit's deployment tool and the tag's application or Runner code.
+ Every stage API-only candidate (tag, SHA or PR merge commit) must support the worker role and register CloudAppWorker.
+ The workflow checks the selected commit before building images. For example, `v0.16.1` passes and `v0.16.0` is refused.
+ For prod in Backoffice, select
+ `prod` and a published stable GitHub Release containing the production-capable Secret Server image. Use the same
+ release for preview and apply, with protected-stage confirmation on apply. Full rollbacks also need a compatible image.
+2. Preview `components=api+runner`. Check the plan for the dedicated database on the existing instance, the two internal services,
+ the per-service invokers and the secret references. Where alerts are enabled, check the incident channel on each policy.
+ Apply the reviewed revision using the same inputs.
+3. Keep `SECRET_SERVER_ENABLED` absent or `false` on the deployed API revision. From the corresponding authorized workload in the VPC,
+ request each service's `/ready` with a Google ID token for that service URL. Record only the status and revision.
+ Cross-call using the other workload's identity and a fresh token for the destination to verify IAM denial.
+4. Inspect the schema from an authorized SQL session with the query below. Both revisions complete startup only after running migrations
+ and reading back the encrypted canary. A second successful startup with the pinned key checks persistence.
+
+```sh
+gh workflow run mdeploy-all.yml --repo boxlite-ai/boxlite --ref "$DEPLOY_BRANCH" \
+ -f stage=dev -f ref="#$PR_NUMBER" -f components=api+runner -f apply=false
+gh workflow run mdeploy-all.yml --repo boxlite-ai/boxlite --ref main \
+ -f stage=stage -f ref="$RELEASE_TAG" -f components=api+runner -f apply=false
+```
+
+```sql
+SELECT current_database(), current_user,
+ (SELECT max(version_id) FROM goose_db_version WHERE is_applied) AS migration_version,
+ EXISTS (SELECT FROM key_verification_canary WHERE id = 1) AS canary_present;
+```
+
+Expect `boxlite_secrets`, `boxlite`, the image's migration version and `true`. Both authorized readiness requests return HTTP 200.
+Keep the Actions run, resolved SHA, revision names and status codes with the acceptance result.
+Run Box E2E after the write handler, fetch handler and v2 Runner are deployed to dev.
diff --git a/apps/infra/mdeploy/pulumi/program.ts b/apps/infra/mdeploy/pulumi/program.ts
index a737effa5..63c8dc5c0 100644
--- a/apps/infra/mdeploy/pulumi/program.ts
+++ b/apps/infra/mdeploy/pulumi/program.ts
@@ -22,6 +22,7 @@
* credentials to deploy at all.
*/
+import type { Components } from '../src/components.ts'
import { readStackEnvironment } from '../src/stack-env.ts'
import { gcpRunnerArtifactsBucket, resolveRunnerBinary } from '../stack/runner-binary.ts'
import type { deployStack } from '../stack/index.ts'
@@ -153,6 +154,7 @@ export const installGlobals = ({
}
export type ProgramInput = {
+ components: Components
/** The app and stage this deploy is for. Both name the state it adopts. */
app: string
stage: string
@@ -199,6 +201,7 @@ export const gcpProgram =
region,
project,
zone = null,
+ components,
environment,
cwd,
loadModules: load = loadModules,
@@ -259,6 +262,8 @@ export const gcpProgram =
const outputs = deployStack({
providers: gcpStackProviders({
+ // A Runner-only update targets OS policies and their grant. Those resources consume the Runner archive.
+ releaseImageManifest: components === 'runner' ? undefined : environment.BOXLITE_RELEASE_DIGESTS,
stage,
region,
project,
@@ -275,6 +280,10 @@ export const gcpProgram =
// the API with, so it is read from the one declaration of it.
volumePrefix: config.storage.volumePrefix,
managedClickHouse: stackEnvironment.managedClickHouse,
+ secretServer: {
+ channel: environment.SECRET_SERVER_INCIDENT_CHANNEL,
+ fetchLimit: environment.SECRET_SERVER_FETCH_LIMIT,
+ },
otelOpenapiEnabled: stackEnvironment.otelOpenapiEnabled,
clickStackConsumer: stackEnvironment.clickStackConsumer,
}),
diff --git a/apps/infra/mdeploy/src/pulumi.ts b/apps/infra/mdeploy/src/pulumi.ts
index ac4d637eb..dfef8066b 100644
--- a/apps/infra/mdeploy/src/pulumi.ts
+++ b/apps/infra/mdeploy/src/pulumi.ts
@@ -166,6 +166,7 @@ export type PulumiDeployInput = {
stageEnvironment?: Record<string, string>
log: (line: string) => void
createStackWith?: StackFactory
+ programWith?: typeof gcpProgram
/**
* Who answers what the project already holds for this stage's API host.
*
@@ -189,6 +190,7 @@ export const pulumiDeploy = async ({
stageEnvironment = {},
log,
createStackWith = createStack,
+ programWith = gcpProgram,
lookupAuthorizations,
}: PulumiDeployInput): Promise<number> => {
deploymentComponents({ value: components, home: 'gcp', intent })
@@ -259,7 +261,16 @@ export const pulumiDeploy = async ({
const stack = await createStackWith({
projectName: app,
stackName: stage,
- program: gcpProgram({ app, stage, region: scope.region, project, zone: scope.zone, environment, cwd: config.root }),
+ program: programWith({
+ app,
+ stage,
+ region: scope.region,
+ project,
+ zone: scope.zone,
+ components,
+ environment,
+ cwd: config.root,
+ }),
/*
* The whole stage environment, not only the credentials and the passphrase.
* The engine spawns a provider plugin per provider, and those are the
diff --git a/apps/infra/mdeploy/src/runner-update.ts b/apps/infra/mdeploy/src/runner-update.ts
index 5ef4f634a..12c402fea 100644
--- a/apps/infra/mdeploy/src/runner-update.ts
+++ b/apps/infra/mdeploy/src/runner-update.ts
@@ -47,6 +47,7 @@ import {
type UpgradeOneRequest,
} from './upgrade-runners.ts'
import { encodeUpgradePayload, renderPolicyScripts } from '../stack/runner-upgrade.ts'
+import { ENROLLED_RUNNER_POLICY } from '../stack/runner-enrollment.ts'
import { RUNNER_PORT, runnerNamePrefix, runnerPolicyBatches } from '../stack/runners.ts'
import { resolveRunnerBinary } from '../stack/runner-binary.ts'
import { zoneIn } from '../stack/providers/gcp/index.ts'
@@ -371,8 +372,30 @@ export const updateRunners = async ({
) {
throw new RunnerUpdateError(`${batch.name} does not match the canary rollout; run mdeploy before runner:update`)
}
- if (!Array.isArray(policy.osPolicies) || !policy.osPolicies.some((item: any) => item.id === 'runner-binary')) {
- throw new RunnerUpdateError(`${batch.name} has no runner-binary policy; run mdeploy before runner:update`)
+ const binaryPolicies = policy.osPolicies?.filter(
+ (item: { id: string }) => item.id === ENROLLED_RUNNER_POLICY || item.id === 'runner-binary',
+ )
+ const binaryPolicy = binaryPolicies?.length === 1 ? binaryPolicies[0] : undefined
+ const resources = binaryPolicy?.resourceGroups?.flatMap(
+ (group: { resources: { id: string }[] }) => group.resources,
+ )
+ const swaps = resources?.filter((resource: { id: string }) => resource.id === 'swap-binary')
+ if (swaps?.length !== 1) {
+ throw new RunnerUpdateError(`${batch.name} needs exactly one swap-binary resource; run mdeploy before runner:update`)
+ }
+ // The deployed group may also enroll the host before starting the binary.
+ const scripts = renderPolicyScripts({
+ identity: binary.identity,
+ binary,
+ port: RUNNER_PORT,
+ allowDowngrade,
+ requireServingVersion: resources.some(
+ (resource: { id: string }) => resource.id === 'converge-unit-environment',
+ ),
+ })
+ swaps[0].exec = {
+ validate: { interpreter: 'NONE', script: scripts.validate },
+ enforce: { interpreter: 'NONE', script: scripts.enforce },
}
return policy.osPolicies
})
@@ -381,16 +404,10 @@ export const updateRunners = async ({
upgradeFleetOverPolicy({
targets: batch.hosts.map((host) => host.target),
identity: binary.identity,
- scripts: renderPolicyScripts({
- identity: binary.identity,
- binary,
- port: RUNNER_PORT,
- allowDowngrade,
- }),
project: scope.project as string,
zone,
assignment: batch.name,
- existingPolicies: deployed[index],
+ osPolicies: deployed[index],
run,
sleep,
log,
diff --git a/apps/infra/mdeploy/src/upgrade-runners.ts b/apps/infra/mdeploy/src/upgrade-runners.ts
index 10ba62674..ffdfbb4f4 100644
--- a/apps/infra/mdeploy/src/upgrade-runners.ts
+++ b/apps/infra/mdeploy/src/upgrade-runners.ts
@@ -274,11 +274,10 @@ const upgradeOverSsm = ({
export const upgradeFleetOverPolicy = ({
targets,
identity,
- scripts,
project,
zone,
assignment,
- existingPolicies,
+ osPolicies,
deadlineSeconds = 900,
run,
sleep,
@@ -288,41 +287,18 @@ export const upgradeFleetOverPolicy = ({
/** Instance names, as the reports name them. */
targets: string[]
identity: string
- scripts: { validate: string; enforce: string }
project: string
zone: string
/** The assignment the deploy owns, by name. */
assignment: string
- existingPolicies: { id: string; [key: string]: unknown }[]
+ osPolicies: { id: string }[]
deadlineSeconds?: number
run: RunCommand
sleep: (seconds: number) => void
log: (line: string) => void
writeFile: (contents: string) => string
}): number => {
- const policy = {
- osPolicies: [
- {
- id: 'runner-binary',
- mode: 'ENFORCEMENT',
- resourceGroups: [
- {
- resources: [
- {
- id: 'swap-binary',
- exec: {
- validate: { interpreter: 'NONE', script: scripts.validate },
- enforce: { interpreter: 'NONE', script: scripts.enforce },
- },
- },
- ],
- },
- ],
- },
- ...existingPolicies.filter((policy) => policy.id !== 'runner-binary'),
- ],
- }
- const file = writeFile(JSON.stringify(policy, null, 2))
+ const file = writeFile(JSON.stringify({ osPolicies }, null, 2))
log(`==> declaring ${identity} on ${assignment}`)
const written = run('gcloud', [
'compute',
@@ -367,7 +343,7 @@ export const upgradeFleetOverPolicy = ({
const report = JSON.parse(reported.stdout)
if (
report.osPolicyAssignment?.endsWith(`/${assignment}@${revision}`) &&
- policy.osPolicies.every((expected) =>
+ osPolicies.every((expected) =>
report.osPolicyCompliances?.some(
(item: any) => item.osPolicyId === expected.id && item.complianceState === 'COMPLIANT',
),
diff --git a/apps/infra/mdeploy/stack/database.ts b/apps/infra/mdeploy/stack/database.ts
index 3c99cb577..b01c70c88 100644
--- a/apps/infra/mdeploy/stack/database.ts
+++ b/apps/infra/mdeploy/stack/database.ts
@@ -96,6 +96,8 @@ export type DatabaseBinding =
* opens a TCP connection to a host and there is no platform in between.
*/
connectionName: $util.Output<string>
+ /** Pinned DSN for the separate Secret Server database on participating stages. */
+ secretServerUrlRef?: $util.Output<string>
}
export type Database = {
diff --git a/apps/infra/mdeploy/stack/image.ts b/apps/infra/mdeploy/stack/image.ts
index 399e6b0c3..7dbe2c3ef 100644
--- a/apps/infra/mdeploy/stack/image.ts
+++ b/apps/infra/mdeploy/stack/image.ts
@@ -15,16 +15,15 @@
*/
import { addressesFor, releaseImageDigests, resolveRegistry } from 'mbuild/address'
-import { loadBuildConfig, type BuildConfig } from 'mbuild/config'
+import { deploymentArtifacts, loadBuildConfig, type BuildConfig } from 'mbuild/config'
export type ImagesRequest = {
/** The commit being deployed. mbuild refuses anything but a full SHA. */
tag: string
}
-const imageDigests = (tag: string) => process.env.BOXLITE_RELEASE_DIGESTS
- ? releaseImageDigests(process.env.BOXLITE_RELEASE_DIGESTS, tag)
- : undefined
+const imageDigests = (tag: string, manifest: string | undefined) =>
+ manifest ? releaseImageDigests(manifest, tag) : undefined
/** Artifact name to the address its runtime pulls from. */
export type Images = Record<string, $util.Output<string>>
@@ -37,17 +36,18 @@ export type Images = Record<string, $util.Output<string>>
export const awsImages =
({ stage, region, config = loadBuildConfig() }: { stage: string; region: string; config?: BuildConfig }) =>
(request: ImagesRequest): Images => {
+ const selected = deploymentArtifacts(config, stage)
const accountId = aws.getCallerIdentityOutput({}).accountId
return Object.fromEntries(
- Object.keys(config.artifacts).map((artifact) => [
+ Object.keys(selected.artifacts).map((artifact) => [
artifact,
accountId.apply(
(account: string) =>
addressesFor({
- config,
+ config: selected,
registry: resolveRegistry({ config, stage, region, accountId: account }),
tag: request.tag,
- digests: imageDigests(request.tag),
+ digests: imageDigests(request.tag, process.env.BOXLITE_RELEASE_DIGESTS),
})[artifact]!,
),
]),
@@ -60,16 +60,23 @@ export const gcpImages =
stage,
region,
project,
+ releaseImageManifest,
config = loadBuildConfig(),
}: {
stage: string
region: string
project: string
+ releaseImageManifest?: string
config?: BuildConfig
}) =>
(request: ImagesRequest): Images =>
Object.fromEntries(
Object.entries(
- addressesFor({ config, registry: resolveRegistry({ config, stage, region, project }), tag: request.tag, digests: imageDigests(request.tag) }),
+ addressesFor({
+ config: deploymentArtifacts(config, stage),
+ registry: resolveRegistry({ config, stage, region, project }),
+ tag: request.tag,
+ digests: imageDigests(request.tag, releaseImageManifest),
+ }),
).map(([artifact, address]) => [artifact, $util.output(address)]),
)
diff --git a/apps/infra/mdeploy/stack/index.ts b/apps/infra/mdeploy/stack/index.ts
index 217a44734..00268a361 100644
--- a/apps/infra/mdeploy/stack/index.ts
+++ b/apps/infra/mdeploy/stack/index.ts
@@ -28,6 +28,7 @@ import type { Cache, CacheProvider } from './cache.ts'
import { CACHE_PASSWORD_VARIABLE, cacheEnvironment } from './cache.ts'
import type { ClickHouse, ClickHouseMode, ClickHouseProvider } from './clickhouse.ts'
import { CLICKHOUSE_PASSWORD_VARIABLE, clickHouseEnvironment } from './clickhouse.ts'
+import { SECRET_FETCH_INSTANCE_ID } from './runner-enrollment.ts'
import { DEFAULT_CLICKHOUSE_RETENTION_HOURS } from './clickhouse-retention.ts'
import type { Cluster, ClusterProvider, WorkloadHost } from './cluster.ts'
import type { Collector, CollectorProvider } from './collector.ts'
@@ -56,7 +57,7 @@ import {
registryProxyHostOf,
} from './registry-proxy.ts'
import { runnerApiUrl } from './runner-boot.ts'
-import type { RunnerAssignment, RunnerProvider, RunnerSlot, Runners } from './runners.ts'
+import type { DeploySecretFetch, RunnerAssignment, RunnerProvider, RunnerSlot, Runners } from './runners.ts'
import { API_RUNNER_TOKEN_VARIABLE } from './runners.ts'
import type { Storage, StorageProvider } from './storage.ts'
import type { DeployConfig } from '../src/config.ts'
@@ -74,7 +75,7 @@ const CONTAINER_ROLES = ['api', 'proxy', 'otel-collector'] as const
*/
const imageFor = (
images: Images,
- component: 'api' | 'proxy' | 'otel-collector' | 'registry-proxy',
+ component: 'api' | 'proxy' | 'otel-collector' | 'registry-proxy' | 'secret-server',
): $util.Input<string> => {
const address = images[component]
if (!address) throw new Error(`mbuild published no ${component} image for this commit`)
@@ -130,6 +131,10 @@ export type StackInputs = {
* which is why the bundle can be built before any resource exists.
*/
export type StackProviders = {
+ secretServer?: (input: { network: Network; database: Database; image: $util.Input<string> }) => {
+ writeUrl: $util.Output<string>
+ deployFetch: DeploySecretFetch
+ }
images: (request: ImagesRequest) => Images
network: NetworkProvider
storage: StorageProvider
@@ -282,6 +287,7 @@ export const deployStack = ({
const storage: Storage = providers.storage(config.storage)
const cluster: Cluster = providers.cluster({ network })({ roles: CONTAINER_ROLES })
const database: Database = providers.database({ network })(config.database)
+ const secrets = providers.secretServer?.({ network, database, image: imageFor(images, 'secret-server') })
const cache: Cache = providers.cache({ network })(config.cache)
const clickhouse: ClickHouse = providers.clickhouse({ network })({
...config.clickhouse,
@@ -437,6 +443,7 @@ export const deployStack = ({
const apiEnvironment = {
...baseApiEnvironment,
+ ...(secrets && { SECRET_SERVER_URL: secrets.writeUrl }),
// The first host's token, which is the one row the API seeds itself. Every
// later host is registered explicitly — see `runner-registration.ts`.
[API_RUNNER_TOKEN_VARIABLE]: defaultRunnerToken,
@@ -565,15 +572,20 @@ export const deployStack = ({
secrets: inputs.proxySecrets,
})
- const runnerEnvironment = {
+ const runnerEnvironment: Record<string, $util.Input<string>> = {
...inputs.runnerEnvironment,
OTEL_EXPORTER_OTLP_ENDPOINT: collector.otlpUrl,
}
+ // OS Config publishes the fetch URL and enrolled host identity together.
+ if (secrets) {
+ delete runnerEnvironment.SECRET_SERVER_URL
+ delete runnerEnvironment[SECRET_FETCH_INSTANCE_ID]
+ }
assertOneChannelPerName({
workload: 'runner',
environment: runnerEnvironment,
secrets: inputs.runnerSecrets,
- injected: [],
+ injected: secrets ? ['SECRET_SERVER_URL', SECRET_FETCH_INSTANCE_ID] : [],
})
/*
* What registers the hosts the API will not seed.
@@ -604,6 +616,7 @@ export const deployStack = ({
...config.runners,
nestedVirtualization: true,
fleet,
+ deploySecretFetch: secrets?.deployFetch,
binary: inputs.runnerBinary,
apiUrl: api.address,
otlpUrl: collector.otlpUrl,
diff --git a/apps/infra/mdeploy/stack/providers/gcp/alarms.ts b/apps/infra/mdeploy/stack/providers/gcp/alarms.ts
index f005d4055..2d366033e 100644
--- a/apps/infra/mdeploy/stack/providers/gcp/alarms.ts
+++ b/apps/infra/mdeploy/stack/providers/gcp/alarms.ts
@@ -82,6 +82,7 @@ const watch = ({
notificationChannels,
windowSeconds = DEFAULT_WINDOW_SECONDS,
durationSeconds,
+ runnerLabel,
}: {
resourceName: string
project: string
@@ -96,7 +97,8 @@ const watch = ({
filter: $util.Input<string>
threshold: AlarmThreshold
description: string
- notificationChannels: string[]
+ notificationChannels: $util.Input<string>[]
+ runnerLabel?: string
/**
* How long one aggregation window runs, in seconds. The default is the one
* minute every request-driven alarm here shares; an alarm whose signal is
@@ -119,7 +121,12 @@ const watch = ({
name: metricName,
project,
filter,
- metricDescriptor: { metricKind: 'DELTA', valueType: 'INT64' },
+ metricDescriptor: {
+ metricKind: 'DELTA',
+ valueType: 'INT64',
+ ...(runnerLabel && { labels: [{ key: 'runner_id', valueType: 'STRING' }] }),
+ },
+ ...(runnerLabel && { labelExtractors: { runner_id: runnerLabel } }),
})
const policy = new gcp.monitoring.AlertPolicy(resourceName, {
project,
@@ -129,13 +136,21 @@ const watch = ({
{
displayName: description,
conditionThreshold: {
- filter: metric.name.apply((name: string) => alertPolicyFilter({ metricName: name, resourceType: resourceType.monitoring })),
+ filter: metric.name.apply((name: string) =>
+ alertPolicyFilter({ metricName: name, resourceType: resourceType.monitoring }),
+ ),
comparison: 'COMPARISON_GT',
// One below the threshold with a strict comparison, so "at least N"
// means the same thing here as CloudWatch's GreaterThanOrEqual.
thresholdValue: threshold.threshold - 1,
duration: `${durationSeconds ?? threshold.periods * windowSeconds}s`,
- aggregations: [{ alignmentPeriod: `${windowSeconds}s`, perSeriesAligner: 'ALIGN_DELTA' }],
+ aggregations: [
+ {
+ alignmentPeriod: `${windowSeconds}s`,
+ perSeriesAligner: 'ALIGN_DELTA',
+ ...(runnerLabel && { crossSeriesReducer: 'REDUCE_SUM', groupByFields: ['metric.label.runner_id'] }),
+ },
+ ],
},
},
],
@@ -144,6 +159,61 @@ const watch = ({
return [metric, policy]
}
+export function secretServerAlarms({
+ project,
+ api,
+ fetch,
+ channel,
+ limit = '100',
+}: {
+ project: string
+ api: string
+ fetch: $util.Output<string>
+ channel: string
+ limit?: string
+}) {
+ if (!/^[1-9][0-9]*$/.test(limit) || !Number.isSafeInteger(Number(limit))) {
+ throw new Error('SECRET_SERVER_FETCH_LIMIT must be a positive integer')
+ }
+ const prefix = `projects/${project}/notificationChannels/`
+ if (!channel.startsWith(prefix) || !/^[0-9]+$/.test(channel.slice(prefix.length))) {
+ throw new Error('SECRET_SERVER_INCIDENT_CHANNEL must name a notification channel in the stage project')
+ }
+ const from = (service: string) => `resource.type="cloud_run_revision" AND resource.labels.service_name="${service}"`
+ const fetchLog = (result: string) =>
+ fetch.apply(
+ (service) => `${from(service)} AND textPayload:"secret fetch runner_id=" AND textPayload =~ " result=${result} "`,
+ )
+ const common = { project, resourceType: CLOUD_RUN, notificationChannels: [channel], durationSeconds: 0 }
+ const metric = (artifact: string) => instanceFor({ app: $app.name, stage: $app.stage, artifact })
+ watch({
+ ...common,
+ resourceName: 'SecretServerDecryptFailure',
+ metricName: metric('secret-decrypt-failed'),
+ description: `Secret decryption failed (${$app.stage})`,
+ filter: fetchLog('decrypt_failed'),
+ threshold: { threshold: 1, periods: 1 },
+ })
+ watch({
+ ...common,
+ resourceName: 'SecretServerReplay',
+ metricName: metric('secret-credential-replay'),
+ description: `Secret credential reused (${$app.stage})`,
+ filter: `${from(api)} AND (jsonPayload.msg =~ "^Secret credential replay: credential_id=" OR textPayload:"Secret credential replay: credential_id=")`,
+ threshold: { threshold: 1, periods: 1 },
+ })
+ watch({
+ ...common,
+ resourceName: 'SecretServerRunnerVolume',
+ metricName: metric('secret-runner-fetches'),
+ description: `High secret fetch count for one Runner (${$app.stage})`,
+ filter: fetchLog('ok'),
+ runnerLabel: 'REGEXP_EXTRACT(textPayload, "secret fetch runner_id=([^ ]+) ")',
+ threshold: { threshold: Number(limit), periods: 1 },
+ windowSeconds: 300,
+ })
+}
+
export const gcpAlarmProvider =
({
subjects,
diff --git a/apps/infra/mdeploy/stack/providers/gcp/database.ts b/apps/infra/mdeploy/stack/providers/gcp/database.ts
index 525eb4013..d4ed90e0b 100644
--- a/apps/infra/mdeploy/stack/providers/gcp/database.ts
+++ b/apps/infra/mdeploy/stack/providers/gcp/database.ts
@@ -22,6 +22,7 @@
import type { Database, DatabaseProvider, DatabaseRequest } from '../../database.ts'
import type { NetworkBinding } from '../../network.ts'
import { instanceFor } from 'naming'
+import { secretServerVersion } from './secret-server.ts'
/**
* What each requested size answers to, and the edition that tier is legal in.
@@ -52,6 +53,7 @@ export const gcpDatabaseProvider =
project,
region,
clientAccount,
+ deploySecretServer = false,
dependsOn,
}: {
network: Extract<NetworkBinding, { cloud: 'gcp' }>
@@ -59,6 +61,7 @@ export const gcpDatabaseProvider =
region: string
/** The identity granted `cloudsql.client`, from the network's own accounts. */
clientAccount: $util.Output<string>
+ deploySecretServer?: boolean
/**
* The network's own resources, the peering among them. An instance created
* before Private Service Access exists fails with an error about the
@@ -179,6 +182,26 @@ export const gcpDatabaseProvider =
member: clientAccount.apply((email: string) => `serviceAccount:${email}`),
})
+ let secretServerUrlRef: $util.Output<string> | undefined
+ if (deploySecretServer) {
+ const schema = new gcp.sql.Database(
+ 'SecretServerDatabase',
+ {
+ project,
+ instance: instance.name,
+ name: 'boxlite_secrets',
+ },
+ { protect: true },
+ )
+ const url = $util
+ .all([schema.name, instance.connectionName, password.result])
+ .apply(
+ ([db, socket, pass]) =>
+ `postgresql:///${db}?${new URLSearchParams({ host: `/cloudsql/${socket}`, user: USERNAME, password: pass, sslmode: 'disable' })}`,
+ )
+ secretServerUrlRef = secretServerVersion(project, 'DatabaseUrl', 'secret-database-url', url)
+ }
+
return {
connection: {
/*
@@ -211,6 +234,7 @@ export const gcpDatabaseProvider =
passwordRef: version.name,
clientGrant: clientAccount,
connectionName: instance.connectionName,
+ secretServerUrlRef,
},
id: instance.id,
ready: [database, user, version, client],
diff --git a/apps/infra/mdeploy/stack/providers/gcp/index.ts b/apps/infra/mdeploy/stack/providers/gcp/index.ts
index 398cd520a..7f0453afe 100644
--- a/apps/infra/mdeploy/stack/providers/gcp/index.ts
+++ b/apps/infra/mdeploy/stack/providers/gcp/index.ts
@@ -35,6 +35,7 @@ import { gcpRegistryCredentialStoreProvider } from './registry-credentials.ts'
import { gcpRegistryProxyProvider } from './registry-proxy.ts'
import { gcpRunnerProvider } from './runners.ts'
import { gcpStorageProvider } from './storage.ts'
+import { deploySecretServer, type SecretServerSettings } from './secret-server.ts'
const onGcp = <T extends { cloud: string }>(value: T, what: string): Extract<T, { cloud: 'gcp' }> => {
if (value.cloud !== 'gcp') throw new Error(`The GCP stack was handed ${value.cloud} ${what}`)
@@ -83,6 +84,8 @@ export const gcpStackProviders = ({
otelOpenapiEnabled = false,
clickStackConsumer = null,
notificationChannels = [],
+ secretServer = {},
+ releaseImageManifest,
}: {
stage: string
region: string
@@ -115,11 +118,34 @@ export const gcpStackProviders = ({
/** Who may read the ClickHouse reader password; see `clickstack.ts`. */
clickStackConsumer?: string | null
notificationChannels?: string[]
+ secretServer?: SecretServerSettings
+ releaseImageManifest?: string
}): StackProviders => {
const zone = zoneIn(region, declaredZone)
+ const secretServerEnvironment = new Map([
+ ['dev', 'dev'],
+ ['stage', 'staging'],
+ ['prod', 'production'],
+ ]).get(stage)
return {
- images: gcpImages({ stage, region, project }),
+ images: gcpImages({ stage, region, project, releaseImageManifest }),
+ ...(secretServerEnvironment && {
+ secretServer: ({ network, database, image }) =>
+ deploySecretServer({
+ project,
+ region,
+ appShort,
+ domain,
+ database,
+ image,
+ settings: secretServer,
+ environment: secretServerEnvironment,
+ subnetwork: placement(network, 'api').subnetwork,
+ apiAccount: placement(network, 'api').serviceAccount,
+ runnerAccount: placement(network, 'runner').serviceAccount,
+ }),
+ }),
network: gcpNetworkProvider({ project, region, appShort }),
storage: gcpStorageProvider({ project, region, appShort }),
// Cloud Run hosts the API, the collector and the registry proxy; GKE exists
@@ -131,6 +157,7 @@ export const gcpStackProviders = ({
project,
region,
clientAccount: placement(network, 'api').serviceAccount,
+ deploySecretServer: secretServerEnvironment !== undefined,
dependsOn: network.ready,
}),
cache: ({ network }) =>
diff --git a/apps/infra/mdeploy/stack/providers/gcp/runners.ts b/apps/infra/mdeploy/stack/providers/gcp/runners.ts
index b068ab0f9..235de79e3 100644
--- a/apps/infra/mdeploy/stack/providers/gcp/runners.ts
+++ b/apps/infra/mdeploy/stack/providers/gcp/runners.ts
@@ -31,6 +31,12 @@
* one with it would take every box running on it.
*/
+import { randomUUID } from 'node:crypto'
+import {
+ checkSecretFetchEnrollment,
+ ENROLLED_RUNNER_POLICY,
+ SECRET_FETCH_INSTANCE_ID,
+} from '../../runner-enrollment.ts'
import type { Placement } from '../../network.ts'
import type { RunnerProvider, RunnerRequest, Runners } from '../../runners.ts'
import { RUNNER_PORT, RUNNER_TOKEN_VARIABLE, runnerDataDiskNameFor, runnerPolicyBatches } from '../../runners.ts'
@@ -162,8 +168,11 @@ export const runnerLabelValue = (controlPlaneRunnerName: string): string =>
* boot the service account's grants may not have propagated, and a host that
* gave up would run without the credentials it needs rather than not run.
*/
-const startWrapper = (secrets: { name: string; secret: string; version: string }[]): BootPlatform['startWrapper'] =>
- secrets.length === 0
+const startWrapper = (
+ secrets: { name: string; secret: string; version: string }[],
+ requireEnrollment: boolean,
+): BootPlatform['startWrapper'] =>
+ secrets.length === 0 && !requireEnrollment
? null
: {
path: '/usr/local/bin/boxlite-runner-start.sh',
@@ -173,6 +182,7 @@ cat > /usr/local/bin/boxlite-runner-start.sh << 'STARTWRAP'
# Re-fetch every secret on each start, so a rotation needs a restart rather
# than a redeploy. Fail-closed: a host that cannot read one does not start.
set -o pipefail
+${requireEnrollment ? checkSecretFetchEnrollment : ''}
fetch() {
local name="$1" secret="$2" version="$3" value=""
for attempt in 1 2 3 4 5; do
@@ -445,6 +455,7 @@ udevadm trigger --name-match=kvm || true`,
return renderRunnerBoot({
apiUrl: apiUrl as string,
otlpUrl: otlpUrl as string,
+ reservedEnvironment: request.deploySecretFetch ? ['SECRET_SERVER_URL', SECRET_FETCH_INSTANCE_ID] : [],
// Plain strings: the binary comes from the checkout, not from another
// resource, so there is nothing here to resolve.
binary: request.binary,
@@ -473,7 +484,7 @@ udevadm trigger --name-match=kvm || true`,
// store delivered. Every host but the first has its own.
[RUNNER_TOKEN_VARIABLE]: hostToken as string,
},
- platform: { ...platform, startWrapper: startWrapper(secrets) },
+ platform: { ...platform, startWrapper: startWrapper(secrets, Boolean(request.deploySecretFetch)) },
})
})
@@ -588,6 +599,85 @@ udevadm trigger --name-match=kvm || true`,
)
})
+ /*
+ * The rows the API will not seed.
+ *
+ * Only when there are any: a single-host fleet is complete the moment the
+ * API is up, and creating a command for it would run a script that has
+ * nothing to do on every deploy. `triggers` is what keeps this from
+ * re-running otherwise — the API's address and the payload are the only two
+ * inputs that change the answer.
+ */
+ const extras = extraRunnersOf(assignments)
+ const registered = [...instances, ...dependsOn]
+ if (extras.length > 0) {
+ const payload = $resolve(extras.map((extra) => extra.token)).apply((tokens) =>
+ registrationPayload({ runners: extras, tokens: tokens as string[] }),
+ )
+ const registration = new command.local.Command(
+ 'RegisterExtraRunners',
+ {
+ // A local command runs from the engine's own cwd, so the directory
+ // has to be given. Derived rather than read from `$cli`, which only
+ // SST defines — see `runner-registration.ts`.
+ dir: registrationDir(),
+ create: REGISTER_RUNNERS_COMMAND,
+ update: REGISTER_RUNNERS_COMMAND,
+ environment: {
+ API_URL: request.apiUrl,
+ // Sealed in state rather than handed over plain. `local.Command`
+ // marks nothing on this resource secret, so an admin-scoped
+ // control-plane key would otherwise be readable in the checkpoint
+ // by anyone who can read the stage's state bucket.
+ ADMIN_API_KEY: $util.secret(adminApiKey),
+ REGION_ID: regionId,
+ RUNNERS: payload,
+ },
+ // Every input that changes the answer, and nothing secret: the
+ // payload carries the tokens, so it is named here by the ids of the
+ // resources that mint them rather than by its own value.
+ triggers: [
+ request.apiUrl,
+ extras.map((extra) => extra.slot.controlPlaneRunnerName).join(','),
+ ],
+ },
+ // After the hosts exist and after the API answers: the script waits on
+ // /api/health, but a row created before its host is a row nothing holds.
+ { dependsOn: [...instances, ...dependsOn] },
+ )
+ registered.push(registration)
+ }
+
+ let fetchUrl = request.environment.SECRET_SERVER_URL
+ let enrolledIds: $util.Output<string[]> | undefined
+ if (request.deploySecretFetch) {
+ // Full apply reads both live identities: a same-name VM or its API row may have been replaced.
+ // A managed command keeps API calls out of previews and untargeted component updates.
+ const lookup = 'node scripts/resolve-gcp-runner-registry.mjs'
+ const identities = assignments.map(({ slot, token }) => ({
+ name: slot.controlPlaneRunnerName,
+ token,
+ vmName: slot.nameTag,
+ }))
+ const registry = new command.local.Command(
+ 'SecretServerRunnerRegistry',
+ {
+ dir: registrationDir(),
+ create: lookup,
+ update: lookup,
+ triggers: [randomUUID()],
+ logging: 'none',
+ addPreviousOutputInEnv: false,
+ environment: { API_URL: request.apiUrl, GCP_PROJECT: project, GCP_ZONE: zone },
+ stdin: $util.secret($jsonStringify(identities)),
+ },
+ { dependsOn: registered },
+ )
+ const fetch = request.deploySecretFetch(registry.stdout)
+ fetchUrl = fetch.url
+ enrolledIds = fetch.enrolledInstanceIds
+ }
+
/*
* How a new binary reaches the hosts above, which the boot script cannot.
*
@@ -614,13 +704,17 @@ udevadm trigger --name-match=kvm || true`,
request.otlpUrl,
request.registryProxyHost ?? '',
request.environment.BOXLITE_RUNNER_ENV ?? '',
- ]).apply(([apiUrl, otlpUrl, proxyHost, runnerEnv]) =>
+ fetchUrl ?? null,
+ enrolledIds ?? null,
+ ]).apply(([apiUrl, otlpUrl, proxyHost, runnerEnv, secretServerUrl, secretFetchInstanceIds]) =>
renderUnitEnvironmentPolicyScripts({
apiUrl: apiUrl as string,
otlpUrl: otlpUrl as string,
volumeBackend: VOLUME_BACKEND,
registryProxyHost: (proxyHost as string) || null,
runnerEnv: runnerEnv as string,
+ secretServerUrl,
+ secretFetchInstanceIds,
// The disks the control plane grows online are named here and
// nowhere else: the policy derives each host's from the same
// function the disk resource below creates under, so a grant or a
@@ -638,10 +732,18 @@ udevadm trigger --name-match=kvm || true`,
validate: unitEnvPolicy.apply((rendered: { validate: string }) => rendered.validate),
enforce: unitEnvPolicy.apply((rendered: { enforce: string }) => rendered.enforce),
}
+ const environmentStep = {
+ id: 'converge-unit-environment',
+ exec: {
+ validate: { interpreter: 'NONE', script: unitEnvScripts.validate },
+ enforce: { interpreter: 'NONE', script: unitEnvScripts.enforce },
+ },
+ }
const scripts = renderPolicyScripts({
identity: request.binary.identity,
binary: request.binary,
port: RUNNER_PORT,
+ requireServingVersion: Boolean(request.deploySecretFetch),
})
let previousBatch: any
for (const batch of runnerPolicyBatches({ app: $app.name, stage: $app.stage }, assignments)) {
@@ -662,11 +764,13 @@ udevadm trigger --name-match=kvm || true`,
},
osPolicies: [
{
- id: 'runner-binary',
+ id: request.deploySecretFetch ? ENROLLED_RUNNER_POLICY : 'runner-binary',
mode: 'ENFORCEMENT',
resourceGroups: [
{
resources: [
+ // OS Config applies resources within a group in order.
+ ...(request.deploySecretFetch ? [environmentStep] : []),
{
id: 'swap-binary',
exec: {
@@ -692,25 +796,15 @@ udevadm trigger --name-match=kvm || true`,
},
],
},
- // The binary and environment policies can restart the runner; the NFS package
- // is independent so a current binary cannot skip installation on an older host.
- {
- id: 'runner-unit-env',
- mode: 'ENFORCEMENT',
- resourceGroups: [
- {
- resources: [
- {
- id: 'converge-unit-environment',
- exec: {
- validate: { interpreter: 'NONE', script: unitEnvScripts.validate },
- enforce: { interpreter: 'NONE', script: unitEnvScripts.enforce },
- },
- },
- ],
- },
- ],
- },
+ ...(request.deploySecretFetch
+ ? []
+ : [
+ {
+ id: 'runner-unit-env',
+ mode: 'ENFORCEMENT',
+ resourceGroups: [{ resources: [environmentStep] }],
+ },
+ ]),
],
rollout: batch.rollout,
skipAwaitRollout: false,
@@ -723,52 +817,5 @@ udevadm trigger --name-match=kvm || true`,
)
}
- /*
- * The rows the API will not seed.
- *
- * Only when there are any: a single-host fleet is complete the moment the
- * API is up, and creating a command for it would run a script that has
- * nothing to do on every deploy. `triggers` is what keeps this from
- * re-running otherwise — the API's address and the payload are the only two
- * inputs that change the answer.
- */
- const extras = extraRunnersOf(assignments)
- if (extras.length > 0) {
- const payload = $resolve(extras.map((extra) => extra.token)).apply((tokens) =>
- registrationPayload({ runners: extras, tokens: tokens as string[] }),
- )
- new command.local.Command(
- 'RegisterExtraRunners',
- {
- // A local command runs from the engine's own cwd, so the directory
- // has to be given. Derived rather than read from `$cli`, which only
- // SST defines — see `runner-registration.ts`.
- dir: registrationDir(),
- create: REGISTER_RUNNERS_COMMAND,
- update: REGISTER_RUNNERS_COMMAND,
- environment: {
- API_URL: request.apiUrl,
- // Sealed in state rather than handed over plain. `local.Command`
- // marks nothing on this resource secret, so an admin-scoped
- // control-plane key would otherwise be readable in the checkpoint
- // by anyone who can read the stage's state bucket.
- ADMIN_API_KEY: $util.secret(adminApiKey),
- REGION_ID: regionId,
- RUNNERS: payload,
- },
- // Every input that changes the answer, and nothing secret: the
- // payload carries the tokens, so it is named here by the ids of the
- // resources that mint them rather than by its own value.
- triggers: [
- request.apiUrl,
- extras.map((extra) => extra.slot.controlPlaneRunnerName).join(','),
- ],
- },
- // After the hosts exist and after the API answers: the script waits on
- // /api/health, but a row created before its host is a row nothing holds.
- { dependsOn: [...instances, ...dependsOn] },
- )
- }
-
return { ids: instances.map((instance) => instance.id), ready: instances }
}
diff --git a/apps/infra/mdeploy/stack/providers/gcp/secret-server.ts b/apps/infra/mdeploy/stack/providers/gcp/secret-server.ts
new file mode 100644
index 000000000..e42557c33
--- /dev/null
+++ b/apps/infra/mdeploy/stack/providers/gcp/secret-server.ts
@@ -0,0 +1,215 @@
+import { identityFor, instanceFor } from 'naming'
+import type { Database } from '../../database.ts'
+import { publicHostsFor } from '../../hosts.ts'
+import { containerEnvironment, secretIdOf } from './secret-env.ts'
+import { secretServerAlarms } from './alarms.ts'
+
+/** The pinned version is the only part of either credential passed to the service graph. */
+export function secretServerVersion(
+ project: string,
+ resource: string,
+ artifact: string,
+ data: $util.Input<string>,
+): $util.Output<string> {
+ const secret = new gcp.secretmanager.Secret(
+ `SecretServer${resource}`,
+ {
+ project,
+ secretId: instanceFor({ app: $app.name, stage: $app.stage, artifact }),
+ replication: { auto: {} },
+ },
+ { protect: true },
+ )
+ return new gcp.secretmanager.SecretVersion(`SecretServer${resource}Value`, {
+ secret: secret.id,
+ secretData: $util.secret(data),
+ deletionPolicy: 'ABANDON',
+ }).name
+}
+
+export type SecretServerSettings = { channel?: string; fetchLimit?: string }
+
+/** Both callers use the destination URL as the audience of their Google ID token. */
+export function secretServerEndpoint(audience: string, uri: string, urls: readonly string[]): string {
+ const endpoint = [uri, ...urls].find((url) => url === audience)
+ if (!endpoint) throw new Error(`Cloud Run did not publish the Secret Server audience ${audience} as a serving URL`)
+ return endpoint
+}
+
+export function deploySecretServer({
+ project,
+ region,
+ appShort,
+ domain,
+ database,
+ image,
+ apiAccount,
+ runnerAccount,
+ subnetwork,
+ settings,
+ environment,
+}: {
+ project: string
+ region: string
+ appShort: string
+ domain: string
+ database: Database
+ image: $util.Input<string>
+ apiAccount: $util.Output<string>
+ runnerAccount: $util.Output<string>
+ subnetwork: $util.Output<string>
+ settings: SecretServerSettings
+ environment: string
+}) {
+ if (database.binding.cloud !== 'gcp' || !database.binding.secretServerUrlRef) {
+ throw new Error('Secret Server requires the GCP boxlite_secrets database')
+ }
+ const connectionName = database.binding.connectionName
+ const urlRef = database.binding.secretServerUrlRef
+ const stage = $app.stage
+ const name = (artifact: string) => instanceFor({ app: $app.name, stage, artifact })
+ const runtime = new gcp.serviceaccount.Account('SecretServerAccount', {
+ project,
+ accountId: identityFor({ appShort, stage, artifact: 'secrets', action: 'run' }),
+ displayName: `BoxLite Secret Server (${stage})`,
+ })
+ const member = $interpolate`serviceAccount:${runtime.email}`
+ const client = new gcp.projects.IAMMember('SecretServerSqlClient', { project, role: 'roles/cloudsql.client', member })
+ const masterKey = new random.RandomBytes('SecretServerMasterKey', { length: 32 }, { protect: true })
+ const keyRef = secretServerVersion(project, 'Key', 'secret-master-key', masterKey.base64)
+ const reads = Object.entries({ Key: keyRef, DatabaseUrl: urlRef }).map(
+ ([id, ref]) =>
+ new gcp.secretmanager.SecretIamMember(`SecretServerRead${id}`, {
+ project,
+ secretId: ref.apply(secretIdOf),
+ role: 'roles/secretmanager.secretAccessor',
+ member,
+ }),
+ )
+
+ const projectNumber = gcp.organizations.getProjectOutput({ projectId: project }).number
+ const service = (
+ role: 'write' | 'fetch',
+ logical: string,
+ caller: $util.Output<string>,
+ values: Record<string, $util.Input<string>>,
+ ) => {
+ const serviceName = name(`secret-${role}`)
+ const audience = $interpolate`https://${serviceName}-${projectNumber}.${region}.run.app`
+ const environmentValues = {
+ ...values,
+ ENVIRONMENT: environment,
+ SECRET_SERVER_ROLE: role,
+ SECRET_SERVER_AUTH_MODE: 'google',
+ SECRET_SERVER_AUDIENCE: audience,
+ SECRET_MASTER_KEY_ID: 'env:v1',
+ }
+ const revision = new gcp.cloudrunv2.Service(
+ logical,
+ {
+ project,
+ location: region,
+ name: serviceName,
+ labels: { stage },
+ customAudiences: [audience],
+ ingress: 'INGRESS_TRAFFIC_INTERNAL_ONLY',
+ deletionProtection: false,
+ scaling: { minInstanceCount: 1 },
+ template: {
+ serviceAccount: runtime.email,
+ scaling: { maxInstanceCount: 2 },
+ vpcAccess: { egress: 'PRIVATE_RANGES_ONLY', networkInterfaces: [{ subnetwork }] },
+ volumes: [{ name: 'cloudsql', cloudSqlInstance: { instances: [connectionName] } }],
+ containers: [
+ {
+ image,
+ ports: { containerPort: 8080 },
+ envs: containerEnvironment({
+ values: environmentValues,
+ addresses: { DATABASE_URL: urlRef, SECRET_MASTER_KEY_BASE64: keyRef },
+ }),
+ volumeMounts: [{ name: 'cloudsql', mountPath: '/cloudsql' }],
+ startupProbe: { httpGet: { path: '/ready', port: 8080 }, periodSeconds: 5, failureThreshold: 36 },
+ },
+ ],
+ },
+ },
+ { dependsOn: [...database.ready, client, ...reads] },
+ )
+ const invoker = new gcp.cloudrunv2.ServiceIamBinding(`${logical}Invoker`, {
+ project,
+ location: region,
+ name: revision.name,
+ role: 'roles/run.invoker',
+ members: [$interpolate`serviceAccount:${caller}`],
+ })
+ const url = $resolve([audience, revision.uri, revision.urls, invoker.id]).apply(([expected, uri, urls]) =>
+ secretServerEndpoint(expected, uri, urls),
+ )
+ return { revision, url }
+ }
+ const write = service('write', 'SecretServerWrite', apiAccount, { SECRET_SERVER_ALLOWED_CALLERS: apiAccount })
+ return {
+ writeUrl: write.url,
+ deployFetch(registry: $util.Output<string>) {
+ const fetch = service('fetch', 'SecretServerFetch', runnerAccount, {
+ SECRET_SERVER_ATTESTORS: 'gcp_iit',
+ SECRET_SERVER_GCP_PROJECT: project,
+ SECRET_SERVER_RUNNER_SERVICE_ACCOUNT: runnerAccount,
+ SECRET_SERVER_RUNNER_REGISTRY: registry,
+ SECRET_SERVER_INTROSPECTION_URL: `https://${publicHostsFor({ domain }).api}/internal/v1/credentials/introspect`,
+ })
+ if (settings.channel) {
+ secretServerAlarms({
+ project,
+ api: name('api'),
+ fetch: fetch.revision.name,
+ channel: settings.channel,
+ limit: settings.fetchLimit,
+ })
+ }
+ // Scoped updates may see a discovery checkpoint newer than the successful Fetch rollout.
+ const {
+ template,
+ latestReadyRevision,
+ latestCreatedRevision,
+ trafficStatuses,
+ generation,
+ observedGeneration,
+ reconciling,
+ } = fetch.revision
+ const enrolledInstanceIds = $util
+ .output({
+ template,
+ latestReadyRevision,
+ latestCreatedRevision,
+ trafficStatuses,
+ generation,
+ observedGeneration,
+ reconciling,
+ })
+ .apply((service) => {
+ const active = service.trafficStatuses.filter((target: { percent: number }) => target.percent > 0)
+ const ready = service.latestReadyRevision
+ if (
+ service.reconciling ||
+ !service.generation ||
+ service.generation !== service.observedGeneration ||
+ !ready ||
+ ready !== service.latestCreatedRevision ||
+ active.length !== 1 ||
+ active[0].percent !== 100 ||
+ active[0].revision?.split('/').pop() !== ready.split('/').pop()
+ ) {
+ throw new Error('Runner enrollment requires a ready Fetch revision serving all traffic')
+ }
+ const registry = service.template.containers[0]?.envs?.find(
+ (env: { name: string }) => env.name === 'SECRET_SERVER_RUNNER_REGISTRY',
+ )
+ if (!registry?.value) throw new Error('The serving Fetch revision has no Runner registry')
+ return Object.keys(JSON.parse(registry.value).gcp_iit)
+ })
+ return { url: fetch.url, enrolledInstanceIds }
+ },
+ }
+}
diff --git a/apps/infra/mdeploy/stack/runner-boot.ts b/apps/infra/mdeploy/stack/runner-boot.ts
index aa2403bfe..29670cd84 100644
--- a/apps/infra/mdeploy/stack/runner-boot.ts
+++ b/apps/infra/mdeploy/stack/runner-boot.ts
@@ -37,7 +37,7 @@
* the wrapper fetches it like any other secret.
*/
-import { registrySetup, runnerInstallLock, recordRunnerDigest } from './runner-registry.ts'
+import { registrySetup, runnerInstallLock, recordRunnerDigest, recordInstalledRunnerVersion } from './runner-registry.ts'
import { fetchVerifiedRunner, type RunnerArtifact } from './runner-binary.ts'
import { kernelDeployment } from './runner-kernel.ts'
import { renderRunnerEnvironment } from './runner-environment.ts'
@@ -85,8 +85,7 @@ export type BootPlatform = {
*/
prepareHome: string
/**
- * A start wrapper that re-fetches every secret the unit needs, or null where
- * the host has none to fetch.
+ * A start wrapper for cloud credentials and host enrollment when required.
*
* A wrapper rather than a one-time fetch so a `systemctl restart` picks up a
* rotated credential, and fail-closed so a host that cannot read one refuses
@@ -103,7 +102,7 @@ export type BootInput = {
/** Where it ships telemetry. */
otlpUrl: string
/** Release candidate or per-commit artifact verified before extracting. */
- binary: RunnerArtifact
+ binary: RunnerArtifact & { identity: string }
/** The region an `s3://` address is read from. Null for a public one. */
region?: string | null
/** The port the runner multiplexes everything onto. */
@@ -111,6 +110,7 @@ export type BootInput = {
/** Values the unit carries beyond what this file decides. */
environment: Record<string, string>
platform: BootPlatform
+ reservedEnvironment?: readonly string[]
}
/**
@@ -126,6 +126,7 @@ export const renderRunnerBoot = (input: BootInput): string => {
const customEnvironment = renderRunnerEnvironment(BOXLITE_RUNNER_ENV, [
...Object.keys(environment),
...Object.keys(platform.unitEnvironment),
+ ...(input.reservedEnvironment ?? []),
])
const region = input.region ?? null
const execStart = platform.startWrapper ? platform.startWrapper.path : '/usr/local/bin/boxlite-runner'
@@ -141,6 +142,9 @@ export const renderRunnerBoot = (input: BootInput): string => {
...platform.unitEnvironment,
}
+ if (!/^[0-9]+\.[0-9]+\.[0-9]+(?:\+[a-f0-9]{40})?$/.test(input.binary.identity)) {
+ throw new Error('Invalid Runner boot identity')
+ }
const script = `#!/bin/bash
exec > /var/log/runner-setup.log 2>&1
# Fail fast and loud: a half-finished bootstrap must not leave a runner that
@@ -170,6 +174,7 @@ ${fetchVerifiedRunner(input.binary, 'boot', region)}
tar -xzf /tmp/boxlite-runner.tar.gz -C /usr/local/bin/
rm -f /tmp/boxlite-runner.tar.gz /tmp/boxlite-runner.sha256
chmod +x /usr/local/bin/boxlite-runner
+${input.binary.release ? recordRunnerDigest : `installed_identity='${input.binary.identity}'\n${recordInstalledRunnerVersion}`}
${kernelDeployment().install}
@@ -217,7 +222,6 @@ mkdir -p ${RUNNER_HOME}
systemctl daemon-reload
systemctl enable boxlite-runner
systemctl start boxlite-runner
-${input.binary.release ? recordRunnerDigest : ''}
echo "Runner setup complete"
`
diff --git a/apps/infra/mdeploy/stack/runner-enrollment.ts b/apps/infra/mdeploy/stack/runner-enrollment.ts
new file mode 100644
index 000000000..3efbc6836
--- /dev/null
+++ b/apps/infra/mdeploy/stack/runner-enrollment.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 BoxLite AI
+
+/** OS Config writes the live GCE ID admitted by the serving fetch revision. */
+export const SECRET_FETCH_INSTANCE_ID = 'BOXLITE_SECRET_FETCH_INSTANCE_ID'
+export const ENROLLED_RUNNER_POLICY = 'runner-enrolled-binary'
+
+const readInstanceId =
+ 'curl -fsS --max-time 5 -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/id'
+
+/** A stale OS policy or unit environment must not admit a same-name replacement VM. */
+export const checkSecretFetchEnrollment = `if [[ -z "$SECRET_SERVER_URL" || -z "$${SECRET_FETCH_INSTANCE_ID}" ]] ||
+ ! live_id="$(${readInstanceId})" || [[ "$live_id" != "$${SECRET_FETCH_INSTANCE_ID}" ]]; then
+ echo "Waiting for this GCE instance's Secret Server enrollment" >&2
+ exit 1
+fi`
+
+export function enrolledInstanceEnvironment(ids: readonly string[], url: string): string {
+ if (!ids.length || ids.some((id) => !/^[1-9][0-9]{0,19}$/.test(id))) {
+ throw new Error('Expected decimal GCE instance IDs from the Secret Server registry')
+ }
+ return `live_id="$(${readInstanceId})"
+case "$live_id" in
+ ${ids.join('|')}) ;;
+ *) echo "This GCE instance is missing from the Secret Server registry" >&2; exit 1 ;;
+esac
+FETCH_FILE="$(dirname "$UNIT_ENV_FILE")/secret-fetch.env"
+DROPIN_DIR="\${BOXLITE_RUNNER_UNIT_DIR:-/etc/systemd/system/boxlite-runner.service.d}"
+FETCH_DROPIN="$DROPIN_DIR/50-secret-fetch.conf"
+FETCH_URL_LINE='SECRET_SERVER_URL=${url}'
+printf -v FETCH_SETTINGS '%s\\n%s' "$FETCH_URL_LINE" "${SECRET_FETCH_INSTANCE_ID}=$live_id"
+printf -v FETCH_UNIT '[Service]\\nEnvironmentFile=%s' "$FETCH_FILE"
+
+enrollment_matches() {
+ [ -f "$FETCH_FILE" ] && [ "$(cat "$FETCH_FILE")" = "$FETCH_SETTINGS" ] &&
+ [ -f "$FETCH_DROPIN" ] && [ "$(cat "$FETCH_DROPIN")" = "$FETCH_UNIT" ]
+}
+
+running_with_fetch_url() {
+ local pid setting
+ systemctl is-active --quiet boxlite-runner || return 1
+ pid="$(systemctl show --property=MainPID --value boxlite-runner)" || return 1
+ [[ "$pid" =~ ^[1-9][0-9]*$ ]] || return 1
+ # A startup wrapper may have a PID while still waiting for enrollment.
+ [[ "$(readlink "/proc/$pid/exe")" = /usr/local/bin/boxlite-runner ]] || return 1
+ while IFS= read -r -d '' setting; do
+ [[ "$setting" != "$FETCH_URL_LINE" ]] || return 0
+ done < "/proc/$pid/environ"
+ return 1
+}
+
+install_enrollment() {
+ mkdir -p -m 0750 "$(dirname "$FETCH_FILE")"
+ mkdir -p -m 0755 "$DROPIN_DIR"
+ if [[ ! -e "$FETCH_FILE.pending" ]]; then printf 'reload\\n' > "$FETCH_FILE.pending"; fi
+ local tmp
+ tmp="$(mktemp "$FETCH_FILE.XXXXXX")"
+ printf '%s\\n' "$FETCH_SETTINGS" > "$tmp"
+ mv -f "$tmp" "$FETCH_FILE"
+ tmp="$(mktemp "$FETCH_DROPIN.XXXXXX")"
+ printf '%s\\n' "$FETCH_UNIT" > "$tmp"
+ chmod 0644 "$tmp"
+ mv -f "$tmp" "$FETCH_DROPIN"
+ systemctl daemon-reload
+}`
+}
diff --git a/apps/infra/mdeploy/stack/runner-registry.ts b/apps/infra/mdeploy/stack/runner-registry.ts
index 78c86ec0f..08e30413e 100644
--- a/apps/infra/mdeploy/stack/runner-registry.ts
+++ b/apps/infra/mdeploy/stack/runner-registry.ts
@@ -74,4 +74,14 @@ VERIFY_RUNNER
${curl} -H "Authorization: Bearer $RUNNER_TOKEN" "${runnerRegistry}/blobs/$RUNNER_ARCHIVE" -o "$RUNNER_ARCHIVE_FILE"
printf '%s %s\\n' "\${RUNNER_ARCHIVE#sha256:}" "$RUNNER_ARCHIVE_FILE" | sha256sum -c -`
-export const recordRunnerDigest = `printf '%s\\n' "$RUNNER_MANIFEST $RUNNER_ARCHIVE" > ${runnerDigestFile}.new && mv -f ${runnerDigestFile}.new ${runnerDigestFile}`
+// Installed by the same lock holder that verified and extracted the archive.
+export const installedRunnerVersionFile = '/usr/local/bin/boxlite-runner.installed-version'
+export const writeInstalledRunnerVersion = `printf '%s %s\\n' "$installed_identity" "\${binary_sha%% *}" > ${installedRunnerVersionFile}.new
+mv -f ${installedRunnerVersionFile}.new ${installedRunnerVersionFile}`
+
+export const recordInstalledRunnerVersion = `binary_sha=$(sha256sum /usr/local/bin/boxlite-runner)
+${writeInstalledRunnerVersion}`
+
+export const recordRunnerDigest = `installed_identity=\${RUNNER_TAG#v}
+${recordInstalledRunnerVersion}
+printf '%s\\n' "$RUNNER_MANIFEST $RUNNER_ARCHIVE" > ${runnerDigestFile}.new && mv -f ${runnerDigestFile}.new ${runnerDigestFile}`
diff --git a/apps/infra/mdeploy/stack/runner-upgrade.ts b/apps/infra/mdeploy/stack/runner-upgrade.ts
index fab76d61b..830c14e6e 100644
--- a/apps/infra/mdeploy/stack/runner-upgrade.ts
+++ b/apps/infra/mdeploy/stack/runner-upgrade.ts
@@ -30,11 +30,12 @@
*/
import { RUNNER_ENV_FILE, runnerApiUrl } from './runner-boot.ts'
+import { enrolledInstanceEnvironment, SECRET_FETCH_INSTANCE_ID } from './runner-enrollment.ts'
import { CLOUD_RUNNER_KERNEL, kernelDeployment } from './runner-kernel.ts'
import { renderRunnerEnvironment, RUNNER_ENV_BEGIN, RUNNER_ENV_END } from './runner-environment.ts'
import { dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
-import { registrySetup, runnerInstallLock, recordRunnerDigest, runnerDigestFile } from './runner-registry.ts'
+import { registrySetup, runnerInstallLock, recordRunnerDigest, runnerDigestFile, installedRunnerVersionFile, recordInstalledRunnerVersion, writeInstalledRunnerVersion } from './runner-registry.ts'
import { fetchVerifiedRunner } from './runner-binary.ts'
import { runnerDataDiskNameFor, type RunnerBinary, type RunnerSlot } from './runners.ts'
@@ -159,6 +160,8 @@ export type UpgradeTarget = {
* reasons. Never empty: see `assertUnitEnvironment`.
*/
otlpUrl?: string | null
+ /** The fetch role's published HTTPS endpoint, when the stage deploys Secret Server. */
+ secretServerUrl?: string | null
/**
* Which object store a volume is mounted from, or null where the boot script
* writes no such key. The cloud's answer: only the GCP hosts carry gcsfuse,
@@ -175,6 +178,8 @@ export type UpgradeTarget = {
runnerEnv?: string
/** Force an older binary over a newer one. A real rollback, asked for. */
allowDowngrade?: boolean
+ /** The preceding policy step can restart the unit before its health endpoint is ready. */
+ requireServingVersion?: boolean
}
/**
@@ -291,9 +296,10 @@ const assertUpgradeTarget = (target: UpgradeTarget): void => {
const assertUnitEnvironment = ({
apiUrl,
otlpUrl,
+ secretServerUrl,
volumeBackend,
registryProxyHost,
-}: Pick<UpgradeTarget, 'apiUrl' | 'otlpUrl' | 'volumeBackend' | 'registryProxyHost'>): void => {
+}: Pick<UpgradeTarget, 'apiUrl' | 'otlpUrl' | 'secretServerUrl' | 'volumeBackend' | 'registryProxyHost'>): void => {
if (apiUrl != null && !UNIT_ENV_URL.test(apiUrl)) {
throw new RunnerUpgradeError(
`the control plane's URL reaches a single-quoted assignment and an awk invocation that run as root, ` +
@@ -306,6 +312,9 @@ const assertUnitEnvironment = ({
`the value that silences its exporter; got ${JSON.stringify(otlpUrl)}`,
)
}
+ if (secretServerUrl != null && (!secretServerUrl.startsWith('https://') || !UNIT_ENV_URL.test(secretServerUrl))) {
+ throw new RunnerUpgradeError('the Secret Server fetch URL must be an HTTPS endpoint')
+ }
if (volumeBackend != null && !VOLUME_BACKEND.test(volumeBackend)) {
throw new RunnerUpgradeError(`the volume backend reaches the same two places; got ${JSON.stringify(volumeBackend)}`)
}
@@ -400,7 +409,7 @@ probe_identity() {
* environment after it still runs. Passing the statement rather than a code is
* what keeps one copy of the checks.
*/
-const guards = (target: UpgradeTarget, satisfied: string, kernelCheck = ''): string => `if [ ! -x /usr/local/bin/boxlite-runner ] ||
+const guards = (target: UpgradeTarget, satisfied: string, validatePolicy = false): string => `if [ ! -x /usr/local/bin/boxlite-runner ] ||
[ ! -f /etc/systemd/system/boxlite-runner.service ] ||
{ ! systemctl is-enabled --quiet boxlite-runner 2>/dev/null &&
! systemctl is-active --quiet boxlite-runner; }; then
@@ -410,8 +419,49 @@ fi
${target.binary.release ? registrySetup(target.binary.release) : ''}
CURRENT=$(probe_identity || true)
-echo "current identity: \${CURRENT:-<not serving>}"
-if [ "$CURRENT" = "$TARGET" ]${target.binary.release ? ` && [ "$(cat ${runnerDigestFile} 2>/dev/null)" = "$RUNNER_MANIFEST $RUNNER_ARCHIVE" ]` : ''}${kernelCheck}; then
+${target.requireServingVersion && target.binary.source === 'release' && !target.allowDowngrade ? `for attempt in {1..12}; do
+ [ -z "$CURRENT" ] || break
+ sleep 5
+ CURRENT=$(probe_identity || true)
+done
+if [ -z "$CURRENT" ]; then
+ # A saved version authorizes only a forward repair of the exact installed bytes.
+ if [[ -f ${installedRunnerVersionFile} ]] &&
+ read -r installed checksum < ${installedRunnerVersionFile} &&
+ [[ "$installed" =~ ^[0-9]+\\.[0-9]+\\.[0-9]+(\\+[a-f0-9]{40})?$ && "$checksum" =~ ^[a-f0-9]{64}$ ]] &&
+ actual=$(sha256sum /usr/local/bin/boxlite-runner) && [[ "\${actual%% *}" == "$checksum" ]] &&
+ [[ "\${installed%%+*}" != "$TARGET" && "$(printf '%s\\n' "\${installed%%+*}" "$TARGET" | sort -V | tail -1)" == "$TARGET" ]]; then
+ CURRENT="$installed"
+ else
+ echo "Cannot confirm the running Runner version or verify a forward repair; refusing to replace its binary" >&2
+ exit 1
+ fi
+fi
+` : ''}echo "current identity: \${CURRENT:-<not serving>}"
+if [ "$CURRENT" = "$TARGET" ]${target.binary.release ? ` && [ "$(cat ${runnerDigestFile} 2>/dev/null)" = "$RUNNER_MANIFEST $RUNNER_ARCHIVE" ]` : ''}${validatePolicy ? ' && runner_kernel_matches' : ''}; then
+ ${target.requireServingVersion ? `if [[ ! -f ${installedRunnerVersionFile} ]] ||
+ ! installed_binary_hash=$(sha256sum /usr/local/bin/boxlite-runner) ||
+ [[ "$(cat ${installedRunnerVersionFile} 2>/dev/null)" != "$CURRENT \${installed_binary_hash%% *}" ]]; then
+ ${validatePolicy ? 'exit 101' : `(
+ WORK=$(mktemp -d)
+ trap 'rm -rf "$WORK"' EXIT
+ ${fetchVerifiedRunner(target.binary, 'upgrade', target.region)}
+ tar -xzf "$WORK/runner.tar.gz" -C "$WORK"
+ expected_sha=$(sha256sum "$WORK/boxlite-runner")
+ # Bind the verified archive bytes to the same live MainPID throughout the health check.
+ pid=$(systemctl show --property=MainPID --value boxlite-runner)
+ [[ "$pid" =~ ^[1-9][0-9]*$ ]] || exit 1
+ executable="/proc/$pid/exe"
+ binary_sha=$(sha256sum "$executable")
+ if [[ "\${binary_sha%% *}" != "\${expected_sha%% *}" || "$(probe_identity || true)" != "$TARGET" || "$(systemctl show --property=MainPID --value boxlite-runner)" != "$pid" ||
+ ! "$executable" -ef /usr/local/bin/boxlite-runner ]]; then
+ echo "Cannot verify the serving Runner executable for installation record" >&2
+ exit 1
+ fi
+ installed_identity="$TARGET"
+ ${writeInstalledRunnerVersion}
+ )`}
+ fi` : ''}
echo "already serving $TARGET; leaving the unit untouched"
${satisfied}
fi
@@ -450,7 +500,7 @@ if install -m 0755 "$WORK/boxlite-runner" /usr/local/bin/boxlite-runner \\
&& systemctl start boxlite-runner \\
&& systemctl is-active --quiet boxlite-runner \\
&& wait_for_target; then
- ${target.binary.release ? recordRunnerDigest : ''}
+ ${target.binary.release ? recordRunnerDigest : `installed_identity="$TARGET"\n${recordInstalledRunnerVersion}`}
if [ "$HAD_PREVIOUS" = true ]; then rm -f /usr/local/bin/boxlite-runner.bak; fi
echo "systemd unit: active"
echo "new identity: $(probe_identity)"
@@ -500,7 +550,7 @@ const SHEBANG = '#!/bin/bash\n'
export const renderPolicyScripts = (target: UpgradeTarget): UpgradePolicyScripts => {
assertUpgradeTarget(target)
return {
- validate: `${SHEBANG}${preamble(target)}${kernelDeployment(target.kernel, target.port).setup}${guards(target, 'exit 100', ' && runner_kernel_matches')}echo "runner binary or kernel needs updating"
+ validate: `${SHEBANG}${preamble(target)}${kernelDeployment(target.kernel, target.port).setup}${guards(target, 'exit 100', true)}echo "runner binary or kernel needs updating"
exit 101
`,
/*
@@ -548,11 +598,13 @@ exit 101
export const unitEnvironmentBlock = ({
apiUrl,
otlpUrl,
+ secretServerUrl,
volumeBackend,
registryProxyHost,
runnerEnv,
dataDiskIdentity = null,
-}: Pick<UpgradeTarget, 'otlpUrl' | 'volumeBackend' | 'registryProxyHost' | 'runnerEnv'> & {
+ secretFetchInstanceIds,
+}: Pick<UpgradeTarget, 'otlpUrl' | 'secretServerUrl' | 'volumeBackend' | 'registryProxyHost' | 'runnerEnv'> & {
apiUrl: string
/**
* The fleet's data-disk identity, or null where the cloud's runners keep box
@@ -561,10 +613,17 @@ export const unitEnvironmentBlock = ({
* environment, so a host payload has nothing to select the row with.
*/
dataDiskIdentity?: RunnerDataDiskIdentity | null
+ secretFetchInstanceIds?: readonly string[] | null
}): string => {
- assertUnitEnvironment({ apiUrl, otlpUrl, volumeBackend, registryProxyHost })
+ assertUnitEnvironment({ apiUrl, otlpUrl, secretServerUrl, volumeBackend, registryProxyHost })
if (dataDiskIdentity) assertDataDiskIdentity(dataDiskIdentity)
- const custom = renderRunnerEnvironment(runnerEnv)
+ if (secretFetchInstanceIds && !secretServerUrl) throw new RunnerUpgradeError('Runner enrollment requires a fetch URL')
+ const enrollment = secretFetchInstanceIds && secretServerUrl
+ ? enrolledInstanceEnvironment(secretFetchInstanceIds, secretServerUrl)
+ : ''
+ const reserved = secretServerUrl ? ['SECRET_SERVER_URL'] : []
+ if (secretFetchInstanceIds) reserved.push(SECRET_FETCH_INSTANCE_ID)
+ const custom = renderRunnerEnvironment(runnerEnv, reserved)
// An array, so an optional key is absent rather than empty: an AWS host's
// boot script writes no backend, a caller that supplied no collector has no
// endpoint to enforce, and a stage without a registry proxy has no host to
@@ -574,6 +633,7 @@ export const unitEnvironmentBlock = ({
const expected = [
`'BOXLITE_API_URL=${runnerApiUrl(apiUrl)}'`,
...(otlpUrl ? [`'OTEL_EXPORTER_OTLP_ENDPOINT=${otlpUrl}'`] : []),
+ ...(secretServerUrl && !enrollment ? [`'SECRET_SERVER_URL=${secretServerUrl}'`] : []),
...(volumeBackend ? [`'VOLUME_STORAGE_BACKEND=${volumeBackend}'`] : []),
...(registryProxyHost ? [`'REGISTRY_PROXY_HOST=${registryProxyHost}'`] : []),
...(dataDiskIdentity ? [`'GCP_PROJECT_ID=${dataDiskIdentity.project}'`, `'GCP_ZONE=${dataDiskIdentity.zone}'`] : []),
@@ -620,6 +680,7 @@ UNIT_ENV_EXPECTED+=("RUNNER_DATA_DISK_NAME=$runner_data_disk")
: ''
return `UNIT_ENV_FILE="\${BOXLITE_RUNNER_ENV_FILE:-${RUNNER_ENV_FILE}}"
UNIT_ENV_EXPECTED=(${expected})
+${enrollment}
${dataDisk}
UNIT_ENV_CUSTOM="$(printf '%s' '${Buffer.from(custom.block).toString('base64')}' | base64 -d)"
UNIT_ENV_KEYS='${custom.keys.join(' ')}'
@@ -641,7 +702,6 @@ custom_unit_environment() {
' "$UNIT_ENV_FILE"
}
-${dataDisk}
unit_environment_matches() {
local line current
for line in "\${UNIT_ENV_EXPECTED[@]}"; do
@@ -655,10 +715,15 @@ unit_environment_matches() {
# writes this file itself, and enforcing against a file that does not exist yet
# would restart a unit that has not started once. A disabled but active runner
# still needs its environment converged.
-unit_environment_settled() {
- if [ ! -f "$UNIT_ENV_FILE" ] ||
+unit_bootstrapping() {
+ [ ! -f "$UNIT_ENV_FILE" ] ||
{ ! systemctl is-enabled --quiet boxlite-runner 2>/dev/null &&
- ! systemctl is-active --quiet boxlite-runner; }; then
+ ! systemctl is-active --quiet boxlite-runner; }
+}
+
+unit_environment_settled() {
+ ${enrollment ? 'enrollment_matches && [ ! -e "$FETCH_FILE.pending" ] || return 1' : ''}
+ if unit_bootstrapping; then
echo "still bootstrapping; the boot script writes $UNIT_ENV_FILE itself — nothing to do"
return 0
fi
@@ -715,6 +780,14 @@ rewrite_unit_environment() {
converge_unit_environment() {
if unit_environment_settled; then return 0; fi
+ ${enrollment ? `install_enrollment
+ if unit_bootstrapping || { [[ "$(cat "$FETCH_FILE.pending")" = reload ]] &&
+ unit_environment_matches && running_with_fetch_url; }; then
+ rm -f "$FETCH_FILE.pending"
+ return 0
+ fi
+ # A retry must finish activating any changes made to runner.env below.
+ printf 'restart\\n' > "$FETCH_FILE.pending"` : ''}
# The copy carries BOXLITE_RUNNER_TOKEN, so it is removed on every path out.
cp -a "$UNIT_ENV_FILE" "$UNIT_ENV_FILE.bak"
if ! rewrite_unit_environment || ! unit_environment_matches; then
@@ -725,6 +798,7 @@ converge_unit_environment() {
rm -f "$UNIT_ENV_FILE.bak"
echo "the unit environment named something this stage no longer serves; rewritten"
systemctl restart boxlite-runner
+ ${enrollment ? 'rm -f "$FETCH_FILE.pending"' : ''}
}
`
}
@@ -738,20 +812,11 @@ converge_unit_environment() {
* instance's organization cannot be granted. What it converges, and why a host
* cannot be told any other way, is above `unitEnvironmentBlock`.
*/
-export const renderUnitEnvironmentPolicyScripts = ({
- apiUrl,
- otlpUrl,
- volumeBackend,
- registryProxyHost,
- runnerEnv,
- dataDiskIdentity = null,
-}: Pick<UpgradeTarget, 'otlpUrl' | 'volumeBackend' | 'registryProxyHost' | 'runnerEnv'> & {
- apiUrl: string
- /** See `unitEnvironmentBlock`. The GCP policy names one; nothing else does. */
- dataDiskIdentity?: RunnerDataDiskIdentity | null
-}): UpgradePolicyScripts => {
+export const renderUnitEnvironmentPolicyScripts = (
+ target: Parameters<typeof unitEnvironmentBlock>[0],
+): UpgradePolicyScripts => {
const block = `set -euo pipefail
-${unitEnvironmentBlock({ apiUrl, otlpUrl, volumeBackend, registryProxyHost, runnerEnv, dataDiskIdentity })}`
+${unitEnvironmentBlock(target)}`
return {
validate: `${SHEBANG}${block}
if unit_environment_settled; then exit 100; fi
@@ -793,6 +858,7 @@ ${guards(target, 'return 0')}${swapSequence(target, 'return 0')})
? `${unitEnvironmentBlock({
apiUrl: target.apiUrl,
otlpUrl: target.otlpUrl,
+ secretServerUrl: target.secretServerUrl,
volumeBackend: target.volumeBackend,
registryProxyHost: target.registryProxyHost,
runnerEnv: target.runnerEnv,
diff --git a/apps/infra/mdeploy/stack/runners.ts b/apps/infra/mdeploy/stack/runners.ts
index 3f446bac6..09971ce06 100644
--- a/apps/infra/mdeploy/stack/runners.ts
+++ b/apps/infra/mdeploy/stack/runners.ts
@@ -76,6 +76,11 @@ export type RunnerBinary = RunnerArtifact & {
identity: string
}
+export type DeploySecretFetch = (registry: $util.Output<string>) => {
+ url: $util.Output<string>
+ enrolledInstanceIds: $util.Output<string[]>
+}
+
export type RunnerRequest = {
size: RunnerSize
machineTypes?: Partial<Record<RunnerSize, string>>
@@ -105,6 +110,8 @@ export type RunnerRequest = {
* read on restore. Null on a cloud that keeps none (see `CheckpointArchives`).
*/
checkpointBucket: $util.Output<string> | null
+ /** Publish the fetch service once the registered GCE fleet is known. */
+ deploySecretFetch?: DeploySecretFetch
/** Values every host reads. */
environment: Record<string, $util.Input<string>>
/** Names it reads by reference: its own registration key, and the admin key. */
diff --git a/apps/infra/mdeploy/test/components.test.ts b/apps/infra/mdeploy/test/components.test.ts
index a9dc67309..e7d9176de 100644
--- a/apps/infra/mdeploy/test/components.test.ts
+++ b/apps/infra/mdeploy/test/components.test.ts
@@ -1,16 +1,22 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
+import * as commandSdk from '@pulumi/command'
import * as gcpSdk from '@pulumi/gcp'
+import { loadBuildConfig } from 'mbuild/config'
import { loadConfig } from 'mstage/config'
import { resolveScope } from 'mstage/scope'
import { componentTargets, deploymentComponents, type DeployedResource } from '../src/components.ts'
import { runnerFleetFrom } from '../src/stack-env.ts'
import { gcpRunnerProvider } from '../stack/providers/gcp/runners.ts'
import { resolveRunnerBinary } from '../stack/runner-binary.ts'
+import { awsImages, gcpImages } from '../stack/image.ts'
import { gcpTarget, pulumiDeploy } from '../src/pulumi.ts'
+import { gcpProgram, type ProgramInput } from '../pulumi/program.ts'
+import type { StackOutputs } from '../stack/index.ts'
import { awsTarget } from '../src/sst.ts'
import { run } from '../src/run.ts'
+import { mockRunnerStack } from './support/gcp-runner-stack.ts'
const environment = { MSTAGE_CONFIG: fileURLToPath(new URL('../../.mstage.config.example.json', import.meta.url)) }
const cwd = fileURLToPath(new URL('../..', import.meta.url))
@@ -21,6 +27,11 @@ const stage = scope.stage!
const prefix = `urn:pulumi:${stage}::${app}::`
const identity = { assertUsableFor: async () => {}, childEnvironment: async () => ({ env: {}, expiresAt: null }) }
+const pin = (digit: string) => 'sha256:' + digit.repeat(64)
+const oldImages = { api: pin('1'), proxy: pin('2'), 'otel-collector': pin('3'), 'registry-proxy': pin('4') }
+const allImages = { ...oldImages, 'secret-server': pin('5') }
+const runnerPins = { manifest: pin('6'), archive: pin('7') }
+
class Value {
constructor(readonly value: any) {}
apply(fn: (input: any) => any): Value {
@@ -40,22 +51,27 @@ const unwrap = (input: any): any =>
/** Capture real provider constructor calls, taking resource types from the installed SDK. */
const runnerState = (count: number, build = false) => {
const resources: (DeployedResource & { name: string; options: any })[] = []
- const namespace = (path: string[]): any =>
+ const namespace = (sdk: object, path: string[] = []): any =>
new Proxy(function () {}, {
- get: (_target, key) => namespace([...path, String(key)]),
+ get: (_target, key) => namespace(sdk, [...path, String(key)]),
construct: (_target, [name, args, options]) => {
- const type = path.reduce((value: any, key) => value[key], gcpSdk).__pulumiType as string
+ const type = path.reduce((value: any, key) => value[key], sdk).__pulumiType as string
const resource = { name, type, urn: `${prefix}${type}::${name}`, inputs: unwrap(args), options }
resources.push(resource)
- return { id: output(name), name: output(args.name ?? name) }
+ return {
+ id: output(name),
+ name: output(args.name ?? name),
+ ...(name === 'SecretServerRunnerRegistry' && { stdout: output('{"gcp_iit":{"12345":"runner-uuid"}}') }),
+ }
},
})
Object.assign(globalThis, {
$app: { name: app, stage },
$util: { output, secret: output },
$resolve: (items: any) => output(unwrap(items)),
- gcp: namespace([]),
- command: { local: { Command: class {} } },
+ $jsonStringify: (input: any) => output(JSON.stringify(unwrap(input))),
+ gcp: namespace(gcpSdk),
+ command: namespace(commandSdk),
})
const values = { RUNNERS: String(count) }
const binary = resolveRunnerBinary({
@@ -79,6 +95,7 @@ const runnerState = (count: number, build = false) => {
binary,
fleet: runnerFleetFrom({ environment: values, app, stage }).map((slot) => ({ slot, token: 'synthetic-token' })),
apiUrl: 'https://api.example.test',
+ deploySecretFetch: () => ({ url: $util.output('https://fetch.example.test'), enrolledInstanceIds: $util.output(['12345']) }),
otlpUrl: 'https://otel.example.test',
registryProxyHost: null,
checkpointBucket: null,
@@ -269,6 +286,13 @@ for (const components of ['api', 'runner', 'api+runner'] as const) {
else {
assert.deepEqual(actual.target, componentTargets({ components, app, stage, resources, environment: {} }))
assert.equal(actual.targetDependents, false)
+ const discovery = resources.find((r) => r.urn.endsWith('::SecretServerRunnerRegistry'))!
+ assert.ok(discovery)
+ assert.ok(
+ actual.target.every((target: string) =>
+ target.endsWith('*') ? !discovery.urn.startsWith(target.slice(0, -1)) : target !== discovery.urn,
+ ),
+ )
if (components === 'api')
assert.ok(
actual.target.some((urn: string) => urn.endsWith('::ApiSecretAccess-*')),
@@ -293,6 +317,162 @@ test('AWS adapter refuses a scoped request before identity resolution or SST spa
await assert.rejects(target.run({ components: 'api', log: () => {} }), /AWS\/SST does not support/)
})
+for (const [label, components, images, runner, error] of [
+ ['old manifest, Runner only', 'runner', oldImages, runnerPins, undefined],
+ ['old manifest, full deployment', 'api+runner', oldImages, runnerPins, undefined],
+ ['old manifest, API only', 'api', oldImages, runnerPins, undefined],
+ ['complete manifest, full deployment', 'api+runner', allImages, runnerPins, undefined],
+ [
+ 'invalid Runner manifest digest',
+ 'runner',
+ oldImages,
+ { ...runnerPins, manifest: 'invalid' },
+ /Invalid release candidate pins for Runner/,
+ ],
+ [
+ 'invalid Runner archive digest',
+ 'runner',
+ oldImages,
+ { ...runnerPins, archive: 'invalid' },
+ /Invalid release candidate pins for Runner/,
+ ],
+] as const) {
+ test(`GCP release preview: ${label}`, async (t) => {
+ const tag = 'v1.2.3'
+ const sha = 'a'.repeat(40)
+ const required = Object.entries(config.envSelectGroup).flatMap(([group, keys]) =>
+ keys.filter((key) => !config.envOptional[group]?.includes(key)),
+ )
+ const stageEnvironment = {
+ ...Object.fromEntries(
+ required.map((key) => [
+ key,
+ config.envSelectGroup.secret?.includes(key)
+ ? JSON.stringify({ address: `projects/${scope.project}/secrets/${key}/versions/1` })
+ : 'fixture',
+ ]),
+ ),
+ BOXLITE_IMAGE_TAG: `${tag}-${sha}`,
+ VERSION: tag,
+ BOXLITE_RELEASE_DIGESTS: JSON.stringify({ tag, sha, images, runner }),
+ STACK_DOMAIN: 'dev.example.test',
+ PROXY_DOMAIN: 'proxy.dev.example.test',
+ }
+ // An inline program shares the driver's process. Only the stage manifest selects its images.
+ const previous = {
+ MSTAGE_CONFIG: process.env.MSTAGE_CONFIG,
+ BOXLITE_RELEASE_DIGESTS: process.env.BOXLITE_RELEASE_DIGESTS,
+ }
+ process.env.MSTAGE_CONFIG = environment.MSTAGE_CONFIG
+ process.env.BOXLITE_RELEASE_DIGESTS = JSON.stringify({ tag, sha, images: oldImages, runner: runnerPins })
+ t.after(() => {
+ for (const [key, value] of Object.entries(previous)) {
+ if (value === undefined) delete process.env[key]
+ else process.env[key] = value
+ }
+ })
+
+ const resources = [...runnerState(1), ...apiState()]
+ const logs: string[] = []
+ const programWith = (options: ProgramInput) =>
+ gcpProgram({
+ ...options,
+ loadModules: async () => ({
+ pulumi: { output, interpolate: undefined, jsonStringify: JSON.stringify, all: undefined, secret: output },
+ gcp: {},
+ random: {},
+ cloudflare: {},
+ command: {},
+ kubernetes: {},
+ }),
+ deployStackWith: ({ providers, inputs }) => {
+ const addresses = unwrap(providers.images({ tag: inputs.tag }))
+ assert.deepEqual(inputs.runnerBinary.release?.pins, { ...runnerPins, sha })
+ if (components !== 'runner') {
+ assert.deepEqual(Object.keys(addresses).sort(), Object.keys(oldImages).sort())
+ for (const [artifact, digest] of Object.entries(oldImages))
+ assert.ok(addresses[artifact].endsWith('@' + digest))
+ }
+ return {} as StackOutputs
+ },
+ })
+ const result = await pulumiDeploy({
+ intent: 'diff',
+ components,
+ config,
+ scope,
+ identity,
+ stageEnvironment,
+ state: { bucket: 'test-state' },
+ log: (line) => logs.push(line),
+ programWith,
+ createStackWith: async ({ program }) => ({
+ exportStack: async () => ({ deployment: { resources } }),
+ setAllConfig: async () => {},
+ preview: async (options) => {
+ if (components === 'runner') {
+ const policies = resources.filter((r) => r.type === 'gcp:osconfig/osPolicyAssignment:OsPolicyAssignment')
+ assert.deepEqual(options.target, [
+ ...policies.map((r) => r.urn),
+ prefix + 'gcp:storage/bucketIAMMember:BucketIAMMember::RunnerArtifactsRead*',
+ ])
+ assert.equal(options.targetDependents, false)
+ } else if (components === 'api+runner') assert.equal(options.target, undefined)
+ await program()
+ },
+ up: async () => assert.fail('apply'),
+ destroy: async () => assert.fail('destroy'),
+ refresh: async () => assert.fail('refresh'),
+ }),
+ })
+ assert.equal(result, error ? 1 : 0, logs.join('\n'))
+ if (error) assert.match(logs.join('\n'), error)
+ })
+}
+
+test('AWS dev and prod resolve all four release image pins without Secret Server', (t) => {
+ const awsDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'aws')
+ const saved = process.env.BOXLITE_RELEASE_DIGESTS
+ t.after(() => {
+ if (awsDescriptor) Object.defineProperty(globalThis, 'aws', awsDescriptor)
+ else Reflect.deleteProperty(globalThis, 'aws')
+ if (saved === undefined) delete process.env.BOXLITE_RELEASE_DIGESTS
+ else process.env.BOXLITE_RELEASE_DIGESTS = saved
+ })
+ Object.assign(globalThis, { aws: { getCallerIdentityOutput: () => ({ accountId: output('123456789012') }) } })
+ const build = loadBuildConfig({ cwd, environment })
+ const sha = 'a'.repeat(40)
+ process.env.BOXLITE_RELEASE_DIGESTS = JSON.stringify({ tag: 'v0.16.1', sha, images: oldImages })
+ for (const stage of ['dev', 'prod']) {
+ const addresses = awsImages({ config: build, stage, region: 'us-east-1' })({ tag: 'v0.16.1-' + sha })
+ assert.deepEqual(Object.keys(addresses).sort(), Object.keys(oldImages).sort())
+ for (const [name, digest] of Object.entries(oldImages)) assert.ok(unwrap(addresses[name]).endsWith('@' + digest))
+ }
+})
+
+test('GCP environments that deploy Secret Server require its pinned release image', (t) => {
+ mockRunnerStack(t)
+ const build = loadBuildConfig({ cwd, environment })
+ const sha = 'a'.repeat(40)
+ const tag = 'v1.2.3'
+ for (const stage of ['dev', 'stage', 'prod']) {
+ const resolve = (images: Record<string, string>) => gcpImages({
+ stage,
+ region: scope.region!,
+ project: scope.project!,
+ config: { ...build, stages: { [stage]: build.stages.dev2! } },
+ releaseImageManifest: JSON.stringify({ tag, sha, images, runner: runnerPins }),
+ })({ tag: tag + '-' + sha })
+ assert.throws(() => resolve(oldImages), /missing.*secret-server/i)
+ const addresses = resolve(allImages)
+ assert.deepEqual(Object.keys(addresses).sort(), Object.keys(allImages).sort())
+ for (const [image, digest] of Object.entries(allImages)) {
+ const { value } = addresses[image] as unknown as Value
+ assert.ok(value.endsWith('@' + digest))
+ }
+ }
+})
+
test('the first App deployment requires the full graph before config writes or engine updates', async () => {
const calls: string[] = []
await assert.rejects(
diff --git a/apps/infra/mdeploy/test/gcp-pitfalls.test.ts b/apps/infra/mdeploy/test/gcp-pitfalls.test.ts
index f06966c1e..2512be4a1 100644
--- a/apps/infra/mdeploy/test/gcp-pitfalls.test.ts
+++ b/apps/infra/mdeploy/test/gcp-pitfalls.test.ts
@@ -986,7 +986,7 @@ test('a host that cannot be told the new control-plane name is converged to it',
* recreated, and recreating one loses `/var/lib/boxlite`.
*/
const source = sourceOf('runners')
- assert.match(source, /id: 'runner-unit-env'/, 'nothing converges the unit environment')
+ assert.match(source, /id: 'converge-unit-environment'/, 'nothing converges the unit environment')
assert.match(source, /renderUnitEnvironmentPolicyScripts/)
/*
diff --git a/apps/infra/mdeploy/test/orchestrator.test.ts b/apps/infra/mdeploy/test/orchestrator.test.ts
index 8d06f8cf0..c06d1b2ea 100644
--- a/apps/infra/mdeploy/test/orchestrator.test.ts
+++ b/apps/infra/mdeploy/test/orchestrator.test.ts
@@ -104,7 +104,7 @@ test('a registry that could not be read is not a stage holding nothing', () => {
const plan = jobAt('plan')
assert.match(
plan,
- /mbuild verify -- --tag "\$IMAGE_TAG" --stage "\$STAGE" \|\| held=\$\?/,
+ /mbuild verify -- "\$\{artifact_args\[@\]\}" \|\| held=\$\?/,
'the status is thrown away',
)
assert.match(plan, new RegExp(`elif \\[ "\\$held" -ne ${absent} \\]; then`), 'absence is not told apart')
@@ -250,7 +250,7 @@ test('an image address carries the version when there is one', () => {
// they are different addresses; prod can be narrowed to the release line only
// because of that. Composed once, in the job that resolved the ref.
assert.match(jobAt('resolve'), /printf 'image=%s\\n' "\$\{VERSION:\+\$\{VERSION\}-\}\$\{sha\}"/)
- assert.match(jobAt('plan'), /mbuild verify -- --tag "\$IMAGE_TAG"/, 'the plan asks about a different address')
+ assert.match(jobAt('plan'), /artifact_args=\(--tag "\$IMAGE_TAG" --stage "\$STAGE"\)/, 'the plan asks about a different address')
assert.match(jobAt('deploy'), /BOXLITE_IMAGE_TAG=%s\\n' "\$IMAGE_TAG"/, 'the apply installs a different address')
})
diff --git a/apps/infra/mdeploy/test/release-runner-digest.test.ts b/apps/infra/mdeploy/test/release-runner-digest.test.ts
index 9dc12a597..bff4e8dbe 100644
--- a/apps/infra/mdeploy/test/release-runner-digest.test.ts
+++ b/apps/infra/mdeploy/test/release-runner-digest.test.ts
@@ -2,14 +2,14 @@ import assert from 'node:assert/strict'
import { test } from 'node:test'
import { resolveRunnerBinary } from '../stack/runner-binary.ts'
import { renderRunnerBoot } from '../stack/runner-boot.ts'
-import { renderUpgradePayload, renderHostConvergence, upgradeTrigger } from '../stack/runner-upgrade.ts'
+import { renderUpgradePayload, renderPolicyScripts, renderHostConvergence, upgradeTrigger } from '../stack/runner-upgrade.ts'
import { createHash } from 'node:crypto'
-import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
-import { join } from 'node:path'
+import { existsSync, linkSync, mkdirSync, chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
import { tmpdir } from 'node:os'
-import { spawnSync } from 'node:child_process'
-import { registrySetup, runnerDigestFile } from '../stack/runner-registry.ts'
+import { execFileSync, spawnSync } from 'node:child_process'
+import { registrySetup, recordRunnerDigest, runnerDigestFile } from '../stack/runner-registry.ts'
const sha = 'a'.repeat(40)
function target(manifest: string, archive: string) {
@@ -203,3 +203,128 @@ test('concurrent host installers stop before reading or swapping the installed R
assert.equal(run(false).status, 0, 'lock must release when the installer exits')
}
})
+
+test('an offline enrolled Runner accepts a forward repair only for its verified installed binary', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'runner-offline-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const binary = join(dir, 'boxlite-runner')
+ const unit = join(dir, 'unit')
+ writeFileSync(binary, 'installed bytes', { mode: 0o755 })
+ writeFileSync(unit, '')
+ const onHost = (script: string) => spawnSync('bash', ['-c', [
+ 'systemctl() { return 0; }; curl() { return 22; }; sleep() { :; }',
+ script.replaceAll('/usr/local/bin/boxlite-runner', binary)
+ .replaceAll('/etc/systemd/system/boxlite-runner.service', unit),
+ ].join('\n')], { encoding: 'utf8' })
+ const candidate = { ...target(digest('a'), digest('b')), requireServingVersion: true }
+ const validate = renderPolicyScripts(candidate).validate
+ const installed = (version: string) => {
+ const receipt = registrySetup({ tag: 'v' + version, pins: { manifest: digest('1'), archive: digest('2'), sha } })
+ const result = onHost('set -euo pipefail\n' + receipt + '\n' + recordRunnerDigest)
+ assert.equal(result.status, 0, result.stderr)
+ }
+ assert.equal(onHost(validate).status, 1, 'missing evidence must fail closed')
+ installed('1.2.2')
+ const forward = onHost(validate)
+ assert.equal(forward.status, 101, 'expected OS Config to repair the offline host: ' + forward.stderr)
+ for (const version of ['1.2.3', '1.2.4']) {
+ installed(version)
+ assert.notEqual(onHost(validate).status, 101, version)
+ }
+ installed('1.2.2')
+ writeFileSync(binary, 'manual replacement')
+ assert.equal(onHost(validate).status, 1, 'a stale record cannot authorize a repair')
+})
+
+for (const source of ['release', 'build'] as const) test(`a healthy legacy ${source} Runner verifies its artifact before an offline upgrade`, (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'runner-backfill-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const binary = join(dir, 'runner')
+ const running = join(dir, 'proc/123/exe')
+ mkdirSync(dirname(running), { recursive: true })
+ writeFileSync(binary, 'verified release', { mode: 0o755 })
+ linkSync(binary, running)
+ writeFileSync(join(dir, 'unit'), '')
+ const archive = join(dir, 'archive')
+ const pack = join(dir, 'boxlite-runner')
+ writeFileSync(pack, readFileSync(binary))
+ execFileSync('tar', ['-czf', archive, '-C', dir, 'boxlite-runner'])
+ const hash = (bytes: Buffer | string) => 'sha256:' + createHash('sha256').update(bytes).digest('hex')
+ const layer = hash(readFileSync(archive))
+ const manifest = JSON.stringify({ artifactType: 'application/vnd.boxlite.runner.v1',
+ annotations: { 'org.opencontainers.image.version': 'v1.2.3', 'org.opencontainers.image.revision': sha },
+ layers: [{ digest: layer, mediaType: 'application/gzip' }] })
+ writeFileSync(join(dir, 'manifest'), manifest)
+ const release = target(hash(manifest), layer)
+ const staged = resolveRunnerBinary({ configRoot: process.cwd(),
+ environment: { VERSION: '1.2.3', RUNNER_ARTIFACT_SOURCE: 'build', RUNNER_ARTIFACT_REF: sha },
+ staging: { cloud: 'gcp', bucket: 'runner-stage-artifacts' } })
+ const artifact = source === 'release' ? release.binary : staged
+ writeFileSync(join(dir, 'checksum'), layer.slice(7) + ' ' + staged.tarballName + '\n')
+ const current = { ...release, identity: artifact.identity, binary: artifact, requireServingVersion: true }
+ writeFileSync(binary + '.oci-digest', hash(manifest) + ' ' + layer + '\n')
+ const next = { ...current, identity: '1.2.4', binary: { ...release.binary, identity: '1.2.4',
+ release: { ...release.binary.release!, tag: 'v1.2.4' } } }
+ let healthy = true
+ const run = (script: string) => {
+ const host = script
+ .replaceAll('/usr/local/bin/boxlite-runner', binary)
+ .replaceAll('/etc/systemd/system/boxlite-runner.service', join(dir, 'unit'))
+ .replaceAll('/run/lock/', dir + '/')
+ .replaceAll('/proc/', dir + '/proc/')
+ .replaceAll('runner_kernel_matches() {', 'runner_kernel_matches() { return 0;')
+ const mocks = `systemctl() { case "$1" in show) echo 123 ;; is-enabled|is-active) return 0 ;; *) echo "$*" >> "$MUTATIONS"; return 1 ;; esac; }
+curl() { case "$*" in
+ *127.0.0.1*) [[ "$HEALTHY" == true ]] && echo '{"version":"${current.identity}"}' ;;
+ *ghcr.io/token*) echo '{"token":"fixture"}' ;;
+ */manifests/${hash(manifest)}*) cp "$DIR/manifest" "\${@: -1}" ;;
+ */blobs/${layer}*) cp "$DIR/archive" "\${@: -1}" ;;
+ *) return 22 ;; esac; }
+gcloud() { case "$3" in
+ "${staged.tarballUrl}") cp "$DIR/archive" "$4" ;;
+ "${staged.checksumUrl}") cp "$DIR/checksum" "$4" ;;
+ *) return 1 ;; esac; }
+sleep() { :; }
+export -f systemctl curl sleep gcloud`
+ return spawnSync('bash', ['-c', mocks + '\n' + host], { encoding: 'utf8',
+ env: { ...process.env, DIR: dir, HEALTHY: String(healthy), MUTATIONS: join(dir, 'mutations') } })
+ }
+ const policy = renderPolicyScripts(current)
+ const upgrade = renderPolicyScripts(next)
+ assert.equal(run(policy.validate).status, 101, 'missing installation record needs enforcement')
+ const repaired = run(policy.enforce)
+ assert.equal(repaired.status, 100, repaired.stderr)
+ assert.equal(readFileSync(binary + '.installed-version', 'utf8').trim(),
+ current.identity + ' ' + createHash('sha256').update('verified release').digest('hex'))
+ assert.equal(run(policy.validate).status, 100)
+
+ const currentChecksum = hash(readFileSync(binary)).slice(7)
+ const staleChecksum = hash('different build').slice(7)
+ const record = binary + '.installed-version'
+ for (const [version, checksum] of [['1.2.5', currentChecksum], [current.identity, staleChecksum]]) {
+ writeFileSync(record, `${version} ${checksum}\n`)
+ healthy = false
+ assert.equal(run(upgrade.validate).status, 1, 'a stale record cannot authorize an offline upgrade')
+
+ healthy = true
+ assert.equal(run(policy.validate).status, 101, 'a stale installation record needs enforcement')
+ const refresh = run(policy.enforce)
+ assert.equal(refresh.status, 100, refresh.stderr)
+ assert.equal(readFileSync(record, 'utf8'), `${current.identity} ${currentChecksum}\n`)
+ assert.equal(run(policy.validate).status, 100)
+ }
+ assert.equal(existsSync(join(dir, 'mutations')), false)
+ healthy = false
+ assert.equal(run(upgrade.validate).status, 101)
+ rmSync(binary + '.installed-version')
+ assert.equal(run(upgrade.validate).status, 1)
+ healthy = true
+ rmSync(binary)
+ writeFileSync(binary, 'manual replacement', { mode: 0o755 })
+ assert.notEqual(run(policy.enforce).status, 100)
+ assert.equal(existsSync(binary + '.installed-version'), false)
+ rmSync(running)
+ linkSync(binary, running)
+ assert.notEqual(run(policy.enforce).status, 100, 'same-version replacement must differ from published bytes')
+ assert.equal(existsSync(binary + '.installed-version'), false)
+})
diff --git a/apps/infra/mdeploy/test/runner-boot.test.ts b/apps/infra/mdeploy/test/runner-boot.test.ts
index 0e4348e57..4098a69fb 100644
--- a/apps/infra/mdeploy/test/runner-boot.test.ts
+++ b/apps/infra/mdeploy/test/runner-boot.test.ts
@@ -37,6 +37,7 @@ const render = (overrides: Partial<Parameters<typeof renderRunnerBoot>[0]> = {})
apiUrl: 'https://api.dev.boxlite.ai/',
otlpUrl: 'http://collector:4318',
binary: {
+ identity: '0.10.0',
tarballUrl: 'https://example.invalid/runner-v0.10.0.tar.gz',
checksumUrl: 'https://example.invalid/runner-v0.10.0.tar.gz.sha256',
tarballName: 'runner-v0.10.0.tar.gz',
@@ -111,6 +112,7 @@ test('an s3 address is read with the host’s own role, and needs a region', ()
// A build-mode binary is staged rather than published, so nothing here is
// fetched anonymously — and the region reaches a shell, so it is checked.
const staged = {
+ identity: '0.10.0',
tarballUrl: 's3://boxlite-app-dev-artifacts/runner/abc/runner.tar.gz',
checksumUrl: 's3://boxlite-app-dev-artifacts/runner/abc/runner.tar.gz.sha256',
tarballName: 'runner.tar.gz',
diff --git a/apps/infra/mdeploy/test/runner-payload.test.ts b/apps/infra/mdeploy/test/runner-payload.test.ts
index 0403df2e7..2a59aefff 100644
--- a/apps/infra/mdeploy/test/runner-payload.test.ts
+++ b/apps/infra/mdeploy/test/runner-payload.test.ts
@@ -172,7 +172,7 @@ const target = (overrides: Partial<UpgradeTarget> = {}): UpgradeTarget => ({
*/
const guard = (current: string, wanted: string, { allowDowngrade = false } = {}) => {
const payload = renderUpgradePayload(target({ identity: wanted, allowDowngrade }))
- const fragment = payload.slice(payload.indexOf('live_is_newer() {'), payload.indexOf('WORK=$(mktemp -d)'))
+ const fragment = payload.slice(payload.indexOf('live_is_newer() {'), payload.indexOf('WORK=$(mktemp -d)', payload.indexOf('live_is_newer() {')))
return bash(`TARGET="${wanted}"\nCURRENT="${current}"\nALLOW_DOWNGRADE="${allowDowngrade ? '1' : ''}"\n${fragment}\necho ok`)
}
@@ -212,6 +212,21 @@ test('a host that is not serving is never newer, so an unhealthy one is repaired
assert.match(guard('', '0.10.0').out, /ok/)
})
+test('an enrolled release waits for the running version before deciding to downgrade', () => {
+ const payload = renderUpgradePayload(target({ requireServingVersion: true }))
+ const checks = payload.slice(payload.indexOf('CURRENT=$(probe_identity'), payload.indexOf('WORK=$(mktemp -d)', payload.indexOf('live_is_newer() {')))
+ for (const ready of [true, false]) {
+ const result = bash(`TARGET=0.10.0; ALLOW_DOWNGRADE=0; CURRENT=''; tries=0
+sleep() { tries=$((tries+1)); }
+probe_identity() { [[ ${ready} == true && $tries -gt 0 ]] && echo 0.11.0; }
+${checks}
+echo SWAPPING`)
+ assert.doesNotMatch(result.out, /SWAPPING/, 'missing identity permitted a release swap')
+ if (ready) assert.match(result.out, /refusing to downgrade/)
+ else assert.notEqual(result.code, 0)
+ }
+})
+
test('the refusal is what --allow-downgrade lifts', () => {
const forced = guard('0.10.0', '0.9.5', { allowDowngrade: true })
assert.match(forced.out, /ok/)
@@ -246,7 +261,7 @@ test('the same rendered lines guard both install paths', () => {
renderRunnerBoot({
apiUrl: 'https://api.invalid/',
otlpUrl: 'http://collector:4318',
- binary: { tarballUrl: 'https://x/t.tar.gz', checksumUrl: 'https://x/t.tar.gz.sha256', tarballName: TARBALL, transport: 'https' },
+ binary: { identity: '0.10.0', tarballUrl: 'https://x/t.tar.gz', checksumUrl: 'https://x/t.tar.gz.sha256', tarballName: TARBALL, transport: 'https' },
port: 3003,
environment: {},
platform: {
@@ -568,6 +583,7 @@ test('runner environment changes converge once and removal agrees with fresh boo
otlpUrl: 'http://collector:4318',
port: 3003,
binary: {
+ identity: '0.10.0',
tarballUrl: 'https://example.invalid/runner.tar.gz',
checksumUrl: 'https://example.invalid/runner.tar.gz.sha256',
tarballName: 'runner.tar.gz',
diff --git a/apps/infra/mdeploy/test/runner-registry.test.ts b/apps/infra/mdeploy/test/runner-registry.test.ts
new file mode 100644
index 000000000..ebf224014
--- /dev/null
+++ b/apps/infra/mdeploy/test/runner-registry.test.ts
@@ -0,0 +1,197 @@
+import assert from 'node:assert/strict'
+import { execFileSync, spawn } from 'node:child_process'
+import { chmodSync, copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import https from 'node:https'
+import type { AddressInfo } from 'node:net'
+import { tmpdir } from 'node:os'
+import { delimiter, join } from 'node:path'
+import { text } from 'node:stream/consumers'
+import test from 'node:test'
+import { fileURLToPath } from 'node:url'
+
+import { mockRunnerStack } from './support/gcp-runner-stack.ts'
+
+const clock = fileURLToPath(new URL('./support/discovery-clock.cjs', import.meta.url))
+const command = fileURLToPath(new URL('../../scripts/resolve-gcp-runner-registry.mjs', import.meta.url))
+const first = { vmName: 'boxlite-app-dev-runner', name: 'first', token: 'synthetic-first' }
+const second = { vmName: 'boxlite-app-dev-runner-2', name: 'second', token: 'synthetic-second' }
+const firstUUID = '11111111-1111-4111-8111-111111111111'
+const secondUUID = '22222222-2222-4222-8222-222222222222'
+
+test('registry command pairs each signed-in Runner with its GCE instance and publishes only complete mappings', async (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'runner-registry-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const key = join(dir, 'key.pem')
+ const cert = join(dir, 'cert.pem')
+ execFileSync(
+ 'openssl',
+ [
+ 'req',
+ '-x509',
+ '-newkey',
+ 'rsa:2048',
+ '-nodes',
+ '-days',
+ '1',
+ '-subj',
+ '/CN=localhost',
+ '-addext',
+ 'subjectAltName=IP:127.0.0.1',
+ '-keyout',
+ key,
+ '-out',
+ cert,
+ ],
+ { stdio: 'ignore' },
+ )
+ const rows = new Map([
+ [first.token, { id: firstUUID, name: first.name, apiVersion: '2' }],
+ [second.token, { id: secondUUID, name: second.name, apiVersion: '2' }],
+ ])
+ copyFileSync(fileURLToPath(new URL('./support/discovery-gcloud.cjs', import.meta.url)), join(dir, 'gcloud'))
+ chmodSync(join(dir, 'gcloud'), 0o700)
+ const instancesFile = join(dir, 'instances.json')
+ const callsFile = join(dir, 'gce-calls')
+ const liveIds = { [first.vmName]: '9999999999999999991', [second.vmName]: '9999999999999999992' }
+ const setLive = (ids: Record<string, string>) => writeFileSync(instancesFile, JSON.stringify(ids))
+ setLive(liveIds)
+ let readyAt = 0
+ const apiCalls: { path: string; elapsed: number }[] = []
+ let registrationPending = false
+ let redirectedRequests = 0
+ const server = https.createServer({ key: readFileSync(key), cert: readFileSync(cert) }, (req, res) => {
+ const elapsed = Number(req.headers['x-test-elapsed-ms'] || 0)
+ apiCalls.push({ path: req.url!, elapsed })
+ if (req.url === '/api/health') {
+ assert.equal(req.headers.authorization, undefined)
+ return res.writeHead(elapsed >= readyAt ? 200 : 503).end()
+ }
+ if (elapsed < readyAt) return res.writeHead(503).end()
+ if (req.url === '/unexpected') redirectedRequests++
+ assert.equal(req.method, 'GET')
+ if (req.url !== '/api/runners/me') return res.writeHead(404).end()
+ const token = req.headers.authorization?.replace(/^Bearer /, '') ?? ''
+ if (token === 'malformed') return res.end('synthetic-sensitive-response')
+ if (token === 'redirect') return res.writeHead(307, { location: '/unexpected' }).end()
+ if (registrationPending) {
+ registrationPending = false
+ return res.writeHead(401).end()
+ }
+ const row = rows.get(token)
+ if (!row) return res.writeHead(403).end(token)
+ res.end(JSON.stringify({ ...row, apiKey: token }))
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ t.after(() => new Promise<void>((resolve) => server.close(() => resolve())))
+ const api = `https://127.0.0.1:${(server.address() as AddressInfo).port}`
+ const run = async (
+ fleet: unknown[],
+ environment: Record<string, string> = { API_URL: api, GCP_PROJECT: 'project', GCP_ZONE: 'us-east5-a' },
+ ) => {
+ const child = spawn(process.execPath, ['--require', clock, command], {
+ timeout: 12000,
+ env: {
+ ...process.env,
+ ...environment,
+ NODE_EXTRA_CA_CERTS: cert,
+ PATH: dir + delimiter + process.env.PATH,
+ TEST_GCE_INSTANCES: instancesFile,
+ TEST_GCE_CALLS: callsFile,
+ },
+ })
+ const status = new Promise((resolve) => child.once('close', resolve))
+ child.stdin.end(JSON.stringify(fleet))
+ const [stdout, stderr, code] = await Promise.all([text(child.stdout), text(child.stderr), status])
+ assert.doesNotMatch(stdout + stderr, /synthetic-|apiKey/)
+ return { stdout, stderr, code }
+ }
+ async function denied(fleet: unknown[], reason: RegExp) {
+ const result = await run(fleet)
+ assert.equal(result.code, 1)
+ assert.equal(result.stdout, '')
+ assert.match(result.stderr, reason)
+ }
+ const stack = mockRunnerStack(t)
+ function discover(count: number) {
+ const request = stack.requestFor(count)
+ request.apiUrl = api
+ request.fleet = request.fleet.map((host, i) => ({
+ slot: { ...host.slot, controlPlaneRunnerName: [first, second][i]!.name },
+ token: [first, second][i]!.token,
+ }))
+ stack.provider({ ...request, deploySecretFetch: () => ({ url: stack.output('https://fetch.run.app'), enrolledInstanceIds: stack.output(['12345']) }) })
+ const lookup = stack.resources.get('SecretServerRunnerRegistry')!
+ assert.equal(stack.resources.get('Runner')!.resource.instanceId.value, '12345') // stale checkpoint
+ return run(JSON.parse(lookup.args.stdin.value), lookup.args.environment)
+ }
+ await t.test('uses the live ID for a same-name VM replacement with the original token', async () => {
+ const result = await discover(1)
+ assert.equal(result.code, 0, result.stderr)
+ assert.deepEqual(JSON.parse(result.stdout), { gcp_iit: { [liveIds[first.vmName]!]: firstUUID } })
+ assert.equal(readFileSync(callsFile, 'utf8').trim(), first.vmName)
+ })
+ await t.test('failed GCE lookup on the second VM publishes no mapping', async (t) => {
+ setLive({ [first.vmName]: liveIds[first.vmName]! })
+ writeFileSync(callsFile, '')
+ t.after(() => setLive(liveIds))
+ const result = await discover(2)
+ assert.equal(result.code, 1)
+ assert.equal(result.stdout, '')
+ assert.match(result.stderr, /GCE.*boxlite-app-dev-runner-2/)
+ assert.deepEqual(readFileSync(callsFile, 'utf8').trim().split('\n'), [first.vmName, second.vmName])
+ })
+ await t.test('single Runner waits past the old 15-second retry window', async (t) => {
+ readyAt = 20_000
+ registrationPending = true
+ t.after(() => {
+ readyAt = 0
+ })
+ apiCalls.length = 0
+ const result = await discover(1)
+ assert.equal(result.code, 0, result.stderr)
+ assert.deepEqual(JSON.parse(result.stdout), { gcp_iit: { [liveIds[first.vmName]!]: firstUUID } })
+ assert.equal(apiCalls[0]?.path, '/api/health')
+ const identities = apiCalls.filter((call) => call.path === '/api/runners/me')
+ assert.equal(identities.length, 2, 'retry a pending default Runner registration after health succeeds')
+ assert.ok(identities[0]!.elapsed >= readyAt && identities[1]!.elapsed > identities[0]!.elapsed)
+ })
+ await t.test('unhealthy API reaches its deadline without identity discovery or partial output', async (t) => {
+ readyAt = Infinity
+ t.after(() => {
+ readyAt = 0
+ })
+ apiCalls.length = 0
+ writeFileSync(callsFile, '')
+ const result = await discover(1)
+ assert.equal(result.code, 1)
+ assert.equal(result.stdout, '')
+ assert.match(result.stderr, /api\/health.*5 minutes/)
+ assert.ok(apiCalls.length && apiCalls.every((call) => call.path === '/api/health'))
+ assert.ok(apiCalls.at(-1)!.elapsed >= 295_000 && apiCalls.at(-1)!.elapsed <= 300_000)
+ assert.equal(readFileSync(callsFile, 'utf8'), '')
+ })
+ apiCalls.length = 0
+ const initial = await run([second, first])
+ assert.equal(initial.code, 0, initial.stderr)
+ assert.deepEqual(
+ apiCalls.map((call) => call.path),
+ ['/api/health', '/api/runners/me', '/api/runners/me'],
+ )
+ assert.deepEqual(JSON.parse(initial.stdout), {
+ gcp_iit: { [liveIds[first.vmName]!]: firstUUID, [liveIds[second.vmName]!]: secondUUID },
+ })
+ await denied([], /empty/)
+ setLive({ [first.vmName]: '9.99e18' })
+ await denied([first], /Invalid GCE instance ID/)
+ setLive(liveIds)
+ await denied([first, first], /Duplicate GCE/)
+ await denied([first, { ...second, token: first.token }], /Unexpected registered identity/)
+ await denied([first, { ...second, token: 'synthetic-invalid' }], /403/)
+ await denied([{ ...first, token: 'malformed' }], /Invalid identity response for Runner first/)
+ await denied([{ ...first, token: 'redirect' }], /307/)
+ assert.equal(redirectedRequests, 0)
+ rows.get(second.token)!.id = firstUUID
+ await denied([first, second], /Duplicate registered UUID/)
+ rows.get(second.token)!.id = 'invalid'
+ await denied([first, second], /Unexpected registered identity/)
+})
diff --git a/apps/infra/mdeploy/test/runner-scale-out.test.ts b/apps/infra/mdeploy/test/runner-scale-out.test.ts
index a97eea64a..0c6d77116 100644
--- a/apps/infra/mdeploy/test/runner-scale-out.test.ts
+++ b/apps/infra/mdeploy/test/runner-scale-out.test.ts
@@ -1,63 +1,150 @@
import assert from 'node:assert/strict'
+import { spawnSync } from 'node:child_process'
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import test from 'node:test'
-import type { RunnerRequest } from '../stack/runners.ts'
-import { gcpRunnerProvider } from '../stack/providers/gcp/runners.ts'
-import { resolveRunnerBinary } from '../stack/runner-binary.ts'
+import { mockRunnerStack } from './support/gcp-runner-stack.ts'
test('GCP rollout batches observe one host before updating the fleet', async (t) => {
- const output = (value: any): any => ({ value, apply: (fn: (value: any) => any) => output(fn(value)) })
- const resources = new Map<string, { args: any; options: any; resource: any }>()
- class Resource {
- [key: string]: any
- constructor(name: string, args: any, options: any = {}) {
- resources.set(name, { args, options, resource: this })
- Object.assign(this, args, { id: output(name), name: output(name) })
+ const { output, globals, resources, provider, requestFor, secretInputs } = mockRunnerStack(t)
+ const servingFetch = (url: string, ids: string[] = ['12345']) => ({
+ url: output(url),
+ enrolledInstanceIds: output(ids),
+ })
+ await t.test('GCE identity lookup follows registration and feeds only OS Config with the verified fetch URL', () => {
+ for (const count of [1, 2]) {
+ resources.clear()
+ const request = requestFor(count)
+ request.fleet = request.fleet.map((host, index) => ({ ...host, token: 'test-token-' + index }))
+ const url = 'https://secret-fetch-123.us-east5.run.app'
+ provider({
+ ...request,
+ deploySecretFetch(registry) {
+ assert.equal(registry, resources.get('SecretServerRunnerRegistry')!.resource.stdout)
+ return servingFetch(url)
+ },
+ })
+ const lookup = resources.get('SecretServerRunnerRegistry')!
+ assert.ok(secretInputs.has(lookup.args.stdin), 'Pulumi must encrypt the token-bearing command input')
+ assert.equal(lookup.args.logging, 'none')
+ assert.equal(lookup.args.addPreviousOutputInEnv, false)
+ const { stdin, ...publicInputs } = lookup.args
+ assert.ok(!JSON.stringify(publicInputs).includes('test-token'))
+ assert.deepEqual(JSON.parse(stdin.value), [
+ { name: 'default', token: 'test-token-0', vmName: 'boxlite-app-dev-runner' },
+ ...(count === 2 ? [{ name: 'runner-2', token: 'test-token-1', vmName: 'boxlite-app-dev-runner-2' }] : []),
+ ])
+ for (const host of request.fleet) {
+ const instance = resources.get(host.slot.resourceName)!
+ assert.ok(lookup.options.dependsOn.includes(instance.resource))
+ assert.doesNotMatch(instance.args.metadataStartupScript.value, /^SECRET_SERVER_URL=/m)
+ }
+ if (count === 2) assert.ok(lookup.options.dependsOn.includes(resources.get('RegisterExtraRunners')!.resource))
+ const policy = resources.get('RunnerBinary')!.args.osPolicies.find((p: any) => p.id === 'runner-enrolled-binary')
+ const steps = policy.resourceGroups[0].resources
+ assert.deepEqual(
+ steps.map((step: any) => step.id),
+ ['converge-unit-environment', 'swap-binary'],
+ )
+ assert.match(steps[1].exec.enforce.script, /Cannot confirm the running Runner version/)
+ assert.equal(steps[0].exec.enforce.script.value.match(/'SECRET_SERVER_URL=([^']+)'/)?.[1], url)
}
- }
- const constructors = new Proxy({}, { get: () => Resource })
- const globals = {
- gcp: new Proxy({}, { get: () => constructors }),
- command: { local: constructors },
- $app: { name: 'boxlite-app', stage: 'dev' },
- $util: { output, secret: output },
- $resolve: (values: any[]) => output(values.map((value) => value?.value ?? value)),
- }
- for (const [key, value] of Object.entries(globals)) {
- const previous = Object.getOwnPropertyDescriptor(globalThis, key)
- Object.defineProperty(globalThis, key, { configurable: true, value })
- t.after(() =>
- previous ? Object.defineProperty(globalThis, key, previous) : Reflect.deleteProperty(globalThis, key),
- )
- }
- const provider = gcpRunnerProvider({
- project: 'project',
- zone: 'us-east5-a',
- volumePrefix: 'boxlite-volume',
- artifactsBucket: 'artifacts',
- adminApiKey: 'admin',
- regionId: 'region',
- dependsOn: [],
- placement: { cloud: 'gcp', subnetwork: output('subnet'), serviceAccount: output('[email protected]') } as any,
})
- const requestFor = (count: number): RunnerRequest => ({
- size: 'small',
- rootDiskGb: 100,
- nestedVirtualization: true,
- fleet: Array.from({ length: count }, (_, index) => ({
- slot: {
- resourceName: index ? `Runner-runner-${index + 1}` : 'Runner',
- nameTag: `boxlite-app-dev-runner${index ? `-${index + 1}` : ''}`,
- controlPlaneRunnerName: index ? `runner-${index + 1}` : 'default',
- },
- token: 'test-token',
- })),
- binary: resolveRunnerBinary({ environment: {}, configRoot: '.', readVersion: () => '0.10.8' }),
- apiUrl: 'https://api.dev.example.com',
- otlpUrl: 'http://otel:4317',
- registryProxyHost: null,
- checkpointBucket: null,
- environment: {},
- secrets: {},
+ await t.test('a new VM can start serving jobs only after its live identity and fetch URL converge', (t) => {
+ resources.clear()
+ const url = 'https://fetch.example.test'
+ provider({ ...requestFor(1), deploySecretFetch: () => servingFetch(url, ['44556']) })
+ const boot: string = resources.get('Runner')!.args.metadataStartupScript.value
+ const start = /^ExecStart=(.+)$/m.exec(boot)![1]!
+ const wrapper =
+ start === '/usr/local/bin/boxlite-runner'
+ ? 'exec /usr/local/bin/boxlite-runner'
+ : boot.split("<< 'STARTWRAP'\n")[1]!.split('\nSTARTWRAP\n')[0]!
+ const dir = mkdtempSync(join(tmpdir(), 'runner-admission-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const envFile = join(dir, 'runner.env')
+ writeFileSync(envFile, boot.split("<< 'RUNNERENV'\n")[1]!.split('\nRUNNERENV\n')[0]! + '\n')
+ writeFileSync(join(dir, 'runner'), '#!/bin/sh\nprintf "%s" "$SECRET_SERVER_URL" > "$SERVED"\n', { mode: 0o700 })
+ writeFileSync(join(dir, 'start'), wrapper.replace('exec /usr/local/bin/boxlite-runner', 'exec runner'))
+ writeFileSync(join(dir, 'curl'), '#!/bin/sh\nprintf "%s" "$VM_ID"\n', { mode: 0o700 })
+ const unitDir = join(dir, 'boxlite-runner.service.d')
+ const launch = `set -a; . ./runner.env
+for dropin in "$BOXLITE_RUNNER_UNIT_DIR"/*.conf; do
+ if [[ -f "$dropin" ]]; then . "$(sed -n 's/^EnvironmentFile=//p' "$dropin")"; fi
+done
+exec bash ./start`
+ writeFileSync(join(dir, 'systemctl'), `#!/usr/bin/env bash\nif [ "$1" = restart ]; then ${launch}; fi\n`, {
+ mode: 0o700,
+ })
+ const served = join(dir, 'served')
+ const execute = (script: string, id: string) =>
+ spawnSync('bash', ['-c', script], {
+ cwd: dir,
+ encoding: 'utf8',
+ env: {
+ PATH: dir + ':' + process.env.PATH,
+ VM_ID: id,
+ BOXLITE_RUNNER_HOST_NAME: 'boxlite-app-dev-runner',
+ BOXLITE_RUNNER_ENV_FILE: envFile,
+ BOXLITE_RUNNER_UNIT_DIR: unitDir,
+ SERVED: served,
+ },
+ })
+ assert.notEqual(execute(launch, '44556').status, 0, 'unenrolled Runner started at boot')
+ const policy = resources.get('RunnerBinary')!.args.osPolicies.find((p: any) => p.id === 'runner-enrolled-binary')
+ const { validate, enforce } = policy.resourceGroups[0].resources[0].exec
+ assert.notEqual(execute(enforce.script.value, '12345').status, 100, 'old registry admitted a replacement VM')
+ assert.equal(existsSync(served), false)
+ const activated = execute(enforce.script.value, '44556')
+ assert.equal(activated.status, 100, activated.stderr)
+ assert.equal(readFileSync(served, 'utf8'), url)
+ assert.equal(execute(validate.script.value, '44556').status, 100)
+ const bootEnv = boot.split("<< 'RUNNERENV'\n")[1]!.split('\nRUNNERENV\n')[0]! + '\n'
+ writeFileSync(envFile, bootEnv)
+ assert.equal(execute(launch, '44556').status, 0, 'reboot erased enrollment')
+ assert.notEqual(execute(launch, '12345').status, 0, 'stale enrollment accepted another VM')
+ })
+ await t.test('enrollment is delivered even when OS Config runs before bootstrap', (t) => {
+ resources.clear()
+ provider({ ...requestFor(1), deploySecretFetch: () => servingFetch('https://fetch.example.test') })
+ const policy = resources
+ .get('RunnerBinary')!
+ .args.osPolicies.find((p: any) =>
+ p.resourceGroups[0].resources.some((r: any) => r.id === 'converge-unit-environment'),
+ )
+ const scripts = policy.resourceGroups[0].resources.find((r: any) => r.id === 'converge-unit-environment').exec
+ const dir = mkdtempSync(join(tmpdir(), 'early-runner-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ writeFileSync(join(dir, 'curl'), '#!/bin/sh\necho 12345\n', { mode: 0o700 })
+ writeFileSync(join(dir, 'systemctl'), '#!/bin/sh\n[ "$1" = daemon-reload ]\n', { mode: 0o700 })
+ const exec = (script: string) =>
+ spawnSync('bash', ['-c', script], {
+ encoding: 'utf8',
+ env: {
+ PATH: dir + ':' + process.env.PATH,
+ BOXLITE_RUNNER_ENV_FILE: join(dir, 'etc', 'runner.env'),
+ BOXLITE_RUNNER_HOST_NAME: 'boxlite-app-dev-runner',
+ BOXLITE_RUNNER_UNIT_DIR: join(dir, 'unit.d'),
+ },
+ })
+ assert.equal(exec(scripts.validate.script.value).status, 101, 'fresh VM reported compliant before enrollment')
+ const result = exec(scripts.enforce.script.value)
+ assert.equal(result.status, 100, result.stderr)
+ assert.equal(exec(scripts.validate.script.value).status, 100)
+ assert.equal(existsSync(join(dir, 'etc', 'runner.env')), false)
+ const file = readFileSync(join(dir, 'unit.d', '50-secret-fetch.conf'), 'utf8').match(/^EnvironmentFile=(.+)$/m)![1]!
+ assert.match(readFileSync(file, 'utf8'), /^BOXLITE_SECRET_FETCH_INSTANCE_ID=12345$/m)
+ })
+ await t.test('an old updater cannot overwrite the enrolled Runner policy', () => {
+ resources.clear()
+ provider({ ...requestFor(1), deploySecretFetch: () => servingFetch('https://fetch.example.test') })
+ const policies = resources.get('RunnerBinary')!.args.osPolicies
+ assert.equal(
+ policies.some((p: any) => p.id === 'runner-binary'),
+ false,
+ 'legacy runner:update accepts the assignment and overwrites enrollment',
+ )
})
await t.test('GCP observes the first runner then updates every other runner in parallel', () => {
for (const count of [4, 1, 12]) {
@@ -69,6 +156,9 @@ test('GCP rollout batches observe one host before updating the fleet', async (t)
{ labels: { 'boxlite-runner': 'default', 'boxlite-stage': 'dev' } },
])
assert.equal(canary.args.name, 'boxlite-app-dev-runner-binary')
+ const binaryPolicy = canary.args.osPolicies.find((policy: any) => policy.id === 'runner-binary')
+ assert.deepEqual(binaryPolicy.resourceGroups[0].resources.map((resource: any) => resource.id), ['swap-binary'])
+ assert.ok(canary.args.osPolicies.some((policy: any) => policy.id === 'runner-unit-env'))
assert.ok(
canary.args.osPolicies.some((policy: any) =>
policy.resourceGroups.some((group: any) =>
diff --git a/apps/infra/mdeploy/test/runner-update.test.ts b/apps/infra/mdeploy/test/runner-update.test.ts
index 51b86b142..22c45ed32 100644
--- a/apps/infra/mdeploy/test/runner-update.test.ts
+++ b/apps/infra/mdeploy/test/runner-update.test.ts
@@ -70,7 +70,16 @@ const gcpFleet = (calls: string[][] = []): RunCommand => {
minWaitDuration: fleet ? '0s' : '300s',
},
osPolicies: [
- { id: 'runner-binary', mode: 'ENFORCEMENT' },
+ {
+ id: fleet ? 'runner-binary' : 'runner-enrolled-binary',
+ mode: 'ENFORCEMENT',
+ resourceGroups: [{
+ resources: [
+ ...(fleet ? [] : [{ id: 'converge-unit-environment', exec: { enforce: { script: 'preserve me' } } }]),
+ { id: 'swap-binary', exec: { enforce: { script: 'old binary' } } },
+ ],
+ }],
+ },
{ id: 'runner-unit-env', mode: 'ENFORCEMENT' },
],
}),
@@ -81,7 +90,7 @@ const gcpFleet = (calls: string[][] = []): RunCommand => {
JSON.stringify({
osPolicyAssignment: `projects/p/locations/z/osPolicyAssignments/${args[4]}@new-revision`,
osPolicyCompliances: [
- { osPolicyId: 'runner-binary', complianceState: 'COMPLIANT' },
+ { osPolicyId: args[4]!.endsWith('-fleet') ? 'runner-binary' : 'runner-enrolled-binary', complianceState: 'COMPLIANT' },
{ osPolicyId: 'runner-unit-env', complianceState: 'COMPLIANT' },
],
}),
@@ -236,9 +245,17 @@ test('on GCP the canary is verified before the remaining fleet is updated', asyn
for (const update of updates) {
assert.ok(!update.includes('--async'))
const policy = JSON.parse(readFileSync(update.find((arg) => arg.startsWith('--file='))!.slice(7), 'utf8'))
+ const resources = policy.osPolicies[0].resourceGroups[0].resources
+ assert.deepEqual(
+ resources.slice(0, -1),
+ update[5]!.endsWith('-fleet') ? [] : [{ id: 'converge-unit-environment', exec: { enforce: { script: 'preserve me' } } }],
+ )
+ assert.equal(resources.at(-1).id, 'swap-binary')
+ assert.match(resources.at(-1).exec.enforce.script, /boxlite-runner/)
+ assert.equal(resources.at(-1).exec.enforce.script.includes('Cannot confirm the running Runner version'), !update[5]!.endsWith('-fleet'))
assert.deepEqual(
policy.osPolicies.map((item: any) => item.id),
- ['runner-binary', 'runner-unit-env'],
+ [update[5]!.endsWith('-fleet') ? 'runner-binary' : 'runner-enrolled-binary', 'runner-unit-env'],
)
}
diff --git a/apps/infra/mdeploy/test/runner-upgrade.test.ts b/apps/infra/mdeploy/test/runner-upgrade.test.ts
index 11d51826a..3872e11b0 100644
--- a/apps/infra/mdeploy/test/runner-upgrade.test.ts
+++ b/apps/infra/mdeploy/test/runner-upgrade.test.ts
@@ -13,7 +13,9 @@
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
-import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
import {
@@ -589,6 +591,106 @@ test('a payload converges the collector endpoint as well as the address', () =>
)
})
+test('OS Config repairs a missing or stale fetch URL and leaves a converged Runner running', () => {
+ const secretServerUrl = 'https://boxlite-dev-secret-fetch-123.us-east5.run.app'
+ const settings = { apiUrl: 'https://api.dev.boxlite.ai', secretServerUrl }
+ const scripts = renderUnitEnvironmentPolicyScripts(settings)
+ const directory = mkdtempSync('boxlite-fetch-url-')
+ const file = `${directory}/runner.env`
+ try {
+ writeFileSync(
+ `${directory}/systemctl`,
+ `#!/bin/bash\nif [ "$1" = restart ]; then echo restart >> '${directory}/calls'; fi\n`,
+ { mode: 0o755 },
+ )
+ const run = (script: string) =>
+ spawnSync('bash', ['-c', script], {
+ env: { ...process.env, PATH: `${directory}:${process.env.PATH}`, BOXLITE_RUNNER_ENV_FILE: file },
+ encoding: 'utf8',
+ })
+ for (const initial of ['', 'SECRET_SERVER_URL=https://old.run.app\n']) {
+ writeFileSync(file, `BOXLITE_API_URL=https://api.dev.boxlite.ai/api\nKEEP=1\n${initial}`)
+ assert.equal(run(scripts.validate).status, 101, 'a missing or stale fetch URL must be detected')
+ assert.equal(run(scripts.enforce).status, 100)
+ const lines = readFileSync(file, 'utf8').split('\n')
+ const urls = lines.filter((line) => line.startsWith('SECRET_SERVER_URL='))
+ assert.deepEqual(urls, [`SECRET_SERVER_URL=${secretServerUrl}`])
+ assert.ok(lines.includes('KEEP=1'))
+ assert.equal(run(scripts.validate).status, 100)
+ assert.equal(run(scripts.enforce).status, 100)
+ }
+ assert.deepEqual(readFileSync(`${directory}/calls`, 'utf8').trim().split('\n'), ['restart', 'restart'])
+ } finally {
+ rmSync(directory, { recursive: true, force: true })
+ }
+})
+
+test('the managed fetch address requires HTTPS and cannot be overridden in the Runner environment', () => {
+ const settings = { apiUrl: 'https://api.dev.boxlite.ai', secretServerUrl: 'https://fetch.run.app' }
+ for (const secretServerUrl of ['', 'http://fetch.run.app', "https://fetch.run.app'"]) {
+ const invalid = { ...settings, secretServerUrl }
+ assert.throws(() => renderUnitEnvironmentPolicyScripts(invalid), /Secret Server/)
+ }
+ const conflicting = { ...settings, runnerEnv: '{"SECRET_SERVER_URL":"https://other.run.app"}' }
+ assert.throws(() => renderUnitEnvironmentPolicyScripts(conflicting), /deployment-owned key SECRET_SERVER_URL/)
+})
+
+test('GCP enrollment restarts only a Runner that needs runtime settings or activation', async (t) => {
+ const url = 'https://fetch.run.app'
+ const settings = { apiUrl: 'https://api.boxlite.ai', secretServerUrl: url, secretFetchInstanceIds: ['42'] }
+ const scripts = renderUnitEnvironmentPolicyScripts(settings)
+ for (const [name, liveUrl, program, apiUrl, restarts] of [
+ ['only the enrollment ID is missing', url, 'boxlite-runner', settings.apiUrl, 0],
+ ['the running process uses a stale fetch URL', 'https://old.run.app', 'boxlite-runner', settings.apiUrl, 1],
+ ['the startup wrapper is waiting for enrollment', url, 'boxlite-runner-start.sh', settings.apiUrl, 1],
+ ['the API address also changed', url, 'boxlite-runner', 'https://old-api.boxlite.ai', 1],
+ ] as const) {
+ await t.test(name, (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'runner-enrollment-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const proc = join(dir, 'proc', '17')
+ mkdirSync(proc, { recursive: true })
+ symlinkSync('/usr/local/bin/' + program, join(proc, 'exe'))
+ writeFileSync(join(proc, 'environ'), 'SECRET_SERVER_URL=' + liveUrl + '\0')
+ const envFile = join(dir, 'runner.env')
+ writeFileSync(envFile, `BOXLITE_API_URL=${apiUrl}/api\nSECRET_SERVER_URL=${url}\n`)
+ writeFileSync(join(dir, 'curl'), '#!/bin/sh\necho 42\n', { mode: 0o755 })
+ writeFileSync(
+ join(dir, 'systemctl'),
+ `#!/bin/sh
+echo "$1" >> "$CALLS"
+if [ "$1" = show ]; then echo 17; fi
+`,
+ { mode: 0o755 },
+ )
+ const calls = join(dir, 'calls')
+ const run = (script: string) =>
+ spawnSync('bash', ['-c', script.replaceAll('/proc/', dir + '/proc/')], {
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ PATH: dir + ':' + process.env.PATH,
+ BOXLITE_RUNNER_ENV_FILE: envFile,
+ BOXLITE_RUNNER_UNIT_DIR: join(dir, 'unit.d'),
+ CALLS: calls,
+ },
+ })
+ assert.equal(run(scripts.validate).status, 101)
+ const result = run(scripts.enforce)
+ assert.equal(result.status, 100, result.stderr)
+ assert.equal(run(scripts.validate).status, 100)
+ assert.equal(run(scripts.enforce).status, 100)
+ assert.equal(
+ readFileSync(calls, 'utf8')
+ .split('\n')
+ .filter((verb) => verb === 'restart').length,
+ restarts,
+ )
+ assert.match(readFileSync(join(dir, 'secret-fetch.env'), 'utf8'), /^BOXLITE_SECRET_FETCH_INSTANCE_ID=42$/m)
+ })
+ }
+})
+
test('an empty collector endpoint is refused rather than converged onto', () => {
/*
* Converging onto `` is the defect itself: every host would be rewritten to
@@ -623,7 +725,7 @@ test('the GCP policy resolves the endpoint rather than casting it', () => {
const policy = gcp.slice(gcp.indexOf('const unitEnvPolicy'), gcp.indexOf('const scripts'))
assert.match(
policy,
- /\$resolve\(\[\s*request\.apiUrl,\s*request\.otlpUrl,\s*request\.registryProxyHost \?\? '',\s*request\.environment\.BOXLITE_RUNNER_ENV \?\? '',?\s*\]\)/,
+ /\$resolve\(\[\s*request\.apiUrl,\s*request\.otlpUrl,\s*request\.registryProxyHost \?\? '',\s*request\.environment\.BOXLITE_RUNNER_ENV \?\? '',\s*fetchUrl \?\? null,\s*enrolledIds \?\? null,?\s*\]\)/,
'every address and the Runner environment must be resolved together',
)
assert.match(policy, /otlpUrl: otlpUrl as string/, 'and the resolved one is what reaches the renderer')
diff --git a/apps/infra/mdeploy/test/secret-server.test.ts b/apps/infra/mdeploy/test/secret-server.test.ts
new file mode 100644
index 000000000..602861a33
--- /dev/null
+++ b/apps/infra/mdeploy/test/secret-server.test.ts
@@ -0,0 +1,224 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { fileURLToPath } from 'node:url'
+import * as pulumi from '@pulumi/pulumi'
+import * as gcp from '@pulumi/gcp'
+import * as random from '@pulumi/random'
+import { installGlobals } from '../pulumi/program.ts'
+import type { Network } from '../stack/network.ts'
+import { gcpStackProviders } from '../stack/providers/gcp/index.ts'
+import { secretServerAlarms } from '../stack/providers/gcp/alarms.ts'
+import { secretServerEndpoint } from '../stack/providers/gcp/secret-server.ts'
+
+test('deployment refuses to publish an audience missing from the serving URLs', () => {
+ const write = 'https://write.run.app'
+ const fetch = 'https://fetch.run.app'
+ assert.equal(secretServerEndpoint(fetch, fetch, []), fetch)
+ assert.equal(secretServerEndpoint(fetch, write, [write, fetch]), fetch)
+ assert.throws(() => secretServerEndpoint(fetch, write, [write]), /did not publish/)
+ assert.throws(() => secretServerEndpoint(fetch, write, []), /did not publish/)
+})
+
+test('rejects invalid alert budgets and notification channels outside the stage', () => {
+ const args = { project: 'boxlite-test', channel, api: 'api', fetch: pulumi.output('fetch') as unknown as $util.Output<string> }
+ for (const limit of ['0', '1.5', 'Infinity', '9007199254740992']) {
+ assert.throws(() => secretServerAlarms({ ...args, limit }), /SECRET_SERVER_FETCH_LIMIT/)
+ }
+ assert.throws(
+ () => secretServerAlarms({ ...args, channel: 'projects/other/notificationChannels/1' }),
+ /SECRET_SERVER_INCIDENT_CHANNEL/,
+ )
+})
+
+const project = 'boxlite-test'
+const region = 'us-east5'
+const privateSubnetId = `projects/${project}/regions/${region}/subnetworks/private`
+const channel = `projects/${project}/notificationChannels/123`
+const connectionName = `${project}:${region}:existing-instance`
+const runnerRegistry = '{"gcp_iit":{"12345":"11111111-1111-4111-8111-111111111111"}}'
+const alarms = ['SecretServerDecryptFailure', 'SecretServerReplay', 'SecretServerRunnerVolume']
+
+async function provision(stage: string, configuredChannel?: string, servingRegistry = runnerRegistry) {
+ process.env.MSTAGE_CONFIG ??= fileURLToPath(new URL('../../.mstage.config.example.json', import.meta.url))
+ const inputs = new Map<string, Record<string, any>>()
+ const channelLookups: unknown[] = []
+ await pulumi.runtime.setMocks(
+ {
+ newResource(args) {
+ inputs.set(args.name, args.inputs)
+ const state = { ...args.inputs }
+ let id = args.name
+ if (args.type === 'gcp:secretmanager/secret:Secret') id = `projects/${project}/secrets/${state.secretId}`
+ if (args.type === 'gcp:secretmanager/secretVersion:SecretVersion') state.name = `${state.secret}/versions/7`
+ if (args.name === 'DatabasePassword') state.result = 'test/password'
+ if (args.name === 'SecretServerMasterKey') state.base64 = Buffer.alloc(32, 1).toString('base64')
+ if (args.name === 'Database') state.connectionName = connectionName
+ if (args.name === 'SecretServerAccount') state.email = '[email protected]'
+ if (args.type === 'gcp:cloudrunv2/service:Service') {
+ const deterministic = `https://${state.name}-12345.${region}.run.app`
+ const alias = `https://${state.name}-example.a.run.app`
+ state.uri = args.name === 'SecretServerFetch' ? alias : deterministic
+ state.urls = [alias, deterministic]
+ state.latestReadyRevision = state.latestCreatedRevision = state.name + '-0001'
+ state.generation = state.observedGeneration = '1'
+ state.reconciling = false
+ state.trafficStatuses = [{ revision: state.latestReadyRevision, percent: 100 }]
+ if (args.name === 'SecretServerFetch') {
+ state.template = structuredClone(state.template)
+ state.template.containers[0].envs.find((env: any) => env.name === 'SECRET_SERVER_RUNNER_REGISTRY').value =
+ servingRegistry
+ }
+ }
+ return { id, state }
+ },
+ call: ({ token, inputs: args }) => {
+ if (token.includes('getNotificationChannel')) {
+ channelLookups.push(args.displayName)
+ return { name: channel, enabled: true }
+ }
+ assert.match(token, /getProject/)
+ return { number: '12345' }
+ },
+ },
+ 'boxlite',
+ stage,
+ )
+ installGlobals({
+ app: 'boxlite',
+ stage,
+ modules: { pulumi, gcp, random, cloudflare: {}, command: {}, kubernetes: {} },
+ })
+ const apiAccount = $util.output('[email protected]')
+ const runnerAccount = $util.output('[email protected]')
+ const binding = {
+ cloud: 'gcp' as const,
+ network: $util.output('vpc'),
+ subnetwork: $util.output(`https://www.googleapis.com/compute/v1/${privateSubnetId}`),
+ privateServiceAccess: $util.output('peering'),
+ cidr: $util.output('10.0.0.0/20'),
+ }
+ const endpoints = await pulumi.runtime.runInPulumiStack(async () => {
+ const network: Network = {
+ binding,
+ ready: [],
+ placementFor: (role) => ({
+ cloud: 'gcp',
+ exposure: 'private',
+ subnetwork: $util.output(privateSubnetId),
+ egressSubnetwork: $util.output(`projects/${project}/regions/${region}/subnetworks/cloudrun-egress`),
+ serviceAccount: role === 'api' ? apiAccount : runnerAccount,
+ }),
+ }
+ const providers = gcpStackProviders({
+ project,
+ region,
+ stage,
+ appShort: 'bl',
+ domain: 'example.test',
+ zoneId: 'zone',
+ artifactsBucket: 'artifacts',
+ volumePrefix: 'volumes',
+ secretServer: { channel: configuredChannel },
+ })
+ assert.ok(providers.secretServer)
+ const database = providers.database({ network })({
+ name: 'boxlite',
+ size: 'small',
+ highlyAvailable: false,
+ backupRetentionDays: 1,
+ protected: true,
+ })
+ const services = providers.secretServer({ network, database, image: 'candidate' })
+ const fetch = services.deployFetch($util.output(runnerRegistry))
+ return { writeUrl: services.writeUrl, fetchUrl: fetch.url, enrolledIds: fetch.enrolledInstanceIds }
+ })
+ await pulumi.runtime.disconnect()
+ return { inputs, endpoints, channelLookups }
+}
+
+test('both Secret Server Cloud Run roles attach to the private subnet by resource ID', async () => {
+ const { inputs } = await provision('dev')
+ const interfaces = ['SecretServerWrite', 'SecretServerFetch'].map(
+ (name) => inputs.get(name)!.template.vpcAccess.networkInterfaces,
+ )
+ assert.deepEqual(interfaces, [[{ subnetwork: privateSubnetId }], [{ subnetwork: privateSubnetId }]])
+})
+
+for (const stage of ['dev', 'stage', 'prod']) {
+ test(`${stage} labels both Secret Server roles, keeps each service warm and bounds revision scaling`, async () => {
+ const { inputs } = await provision(stage)
+ for (const name of ['SecretServerWrite', 'SecretServerFetch']) {
+ const service = inputs.get(name)!
+ assert.equal(service.labels?.stage, stage, name)
+ assert.equal(service.scaling?.minInstanceCount, 1, name)
+ assert.equal(service.template.scaling.maxInstanceCount, 2, name)
+ }
+ })
+
+ test(`${stage} without a channel deploys both Secret Server roles and skips alarm resources and channel lookup`, async () => {
+ const { inputs, endpoints, channelLookups } = await provision(stage)
+ assert.ok(endpoints?.writeUrl && endpoints.fetchUrl)
+ assert.deepEqual(channelLookups, [])
+ for (const name of alarms) {
+ assert.equal(inputs.has(name), false, name)
+ assert.equal(inputs.has(name + 'Metric'), false, name + 'Metric')
+ }
+ })
+
+ test(`${stage} with an explicit channel sends every Secret Server alert to it`, async () => {
+ const { inputs, channelLookups } = await provision(stage, channel)
+ assert.deepEqual(channelLookups, [])
+ for (const name of alarms) assert.deepEqual(inputs.get(name)!.notificationChannels, [channel])
+ })
+}
+
+test('both production Cloud Run roles start on the separate SQL database with pinned secrets and distinct invokers', async () => {
+ const { inputs, endpoints, channelLookups } = await provision('prod', channel)
+ assert.deepEqual(channelLookups, [])
+ assert.equal(inputs.get('SecretServerDatabase')!.instance, inputs.get('DatabaseSchema')!.instance)
+ const urlValue = inputs.get('SecretServerDatabaseUrlValue')!.secretData
+ const url = new URL(typeof urlValue === 'string' ? urlValue : urlValue.value)
+ assert.equal(url.searchParams.get('user'), inputs.get('DatabaseUser')!.name)
+ assert.equal(url.pathname, '/boxlite_secrets')
+ assert.equal(url.searchParams.get('host'), `/cloudsql/${connectionName}`)
+ assert.equal(url.searchParams.get('password'), 'test/password')
+ assert.equal(inputs.get('SecretServerMasterKey')!.length, 32)
+ for (const [name, role, caller] of [
+ ['Write', 'write', 'api'],
+ ['Fetch', 'fetch', 'runner'],
+ ]) {
+ const args = inputs.get(`SecretServer${name}`)!
+ assert.equal(args.ingress, 'INGRESS_TRAFFIC_INTERNAL_ONLY')
+ const container = args.template.containers[0]
+ assert.deepEqual(args.template.volumes, [{ name: 'cloudsql', cloudSqlInstance: { instances: [connectionName] } }])
+ assert.deepEqual(container.volumeMounts, [{ name: 'cloudsql', mountPath: '/cloudsql' }])
+ assert.equal(container.image, 'candidate')
+ assert.equal(container.startupProbe.httpGet.path, '/ready')
+ const env = Object.fromEntries(container.envs.map((e: any) => [e.name, e.value ?? e.valueSource?.secretKeyRef]))
+ assert.equal(env.ENVIRONMENT, 'production')
+ assert.equal(env.SECRET_SERVER_ROLE, role)
+ assert.equal(env.SECRET_SERVER_AUDIENCE, `https://${args.name}-12345.${region}.run.app`)
+ assert.equal(endpoints?.[`${role}Url`], env.SECRET_SERVER_AUDIENCE)
+ assert.deepEqual(args.customAudiences, [env.SECRET_SERVER_AUDIENCE])
+ assert.equal(env.SECRET_SERVER_AUTH_MODE, 'google')
+ assert.equal(env.SECRET_MASTER_KEY_BASE64.version, '7')
+ assert.equal(env.DATABASE_URL.version, '7')
+ assert.deepEqual(inputs.get(`SecretServer${name}Invoker`)!.members, [`serviceAccount:${caller}@example.test`])
+ if (role === 'fetch') assert.equal(env.SECRET_SERVER_RUNNER_REGISTRY, runnerRegistry)
+ else assert.equal(env.SECRET_SERVER_ALLOWED_CALLERS, '[email protected]')
+ }
+ for (const name of alarms) {
+ assert.deepEqual(inputs.get(name)!.notificationChannels, [channel])
+ }
+ const policy = inputs.get('SecretServerRunnerVolume')!.conditions[0].conditionThreshold
+ assert.deepEqual(policy.aggregations[0].groupByFields, ['metric.label.runner_id'])
+ assert.equal(policy.aggregations[0].alignmentPeriod, '300s')
+ assert.equal(policy.thresholdValue, 99)
+ assert.match(inputs.get('SecretServerReplayMetric')!.filter, /Secret credential replay/)
+ assert.match(inputs.get('SecretServerDecryptFailureMetric')!.filter, /result=decrypt_failed/)
+})
+
+test('a scoped retry admits only the registry already installed on the serving Fetch revision', async () => {
+ const { endpoints } = await provision('dev', undefined, '{"gcp_iit":{"67890":"existing-runner"}}')
+ assert.deepEqual(endpoints?.enrolledIds, ['67890'])
+})
diff --git a/apps/infra/mdeploy/test/stack.test.ts b/apps/infra/mdeploy/test/stack.test.ts
index fba4b2ed5..118cbe01a 100644
--- a/apps/infra/mdeploy/test/stack.test.ts
+++ b/apps/infra/mdeploy/test/stack.test.ts
@@ -90,6 +90,21 @@ const inputs = (overrides: Partial<StackInputs> = {}): StackInputs => ({
...overrides,
})
+test('the API and Runner receive the endpoints published by their own Secret Server roles', () => {
+ const { providers, seen } = bundle()
+ const writeUrl = out('https://write.run.app')
+ const fetchUrl = out('https://fetch.run.app')
+ const deployFetch = () => ({ url: fetchUrl, enrolledInstanceIds: out(['12345']) })
+ deployStack({
+ providers: { ...providers, secretServer: () => ({ writeUrl, deployFetch }) },
+ config,
+ inputs: { ...inputs(), runnerEnvironment: { SECRET_SERVER_URL: 'https://stale.example.test' } },
+ })
+ assert.equal(seen.api.request.environment.SECRET_SERVER_URL, writeUrl)
+ assert.equal(seen.runners.request.environment.SECRET_SERVER_URL, undefined)
+ assert.equal(seen.runners.request.deploySecretFetch, deployFetch)
+})
+
test('filestore projects become the final API capability', () => {
const { providers, seen } = bundle()
deployStack({
@@ -227,6 +242,7 @@ const bundle = ({
proxy: out(`registry/${request.tag}-proxy`),
'otel-collector': out(`registry/${request.tag}-otel`),
'registry-proxy': out(`registry/${request.tag}-registry-proxy`),
+ 'secret-server': out(`registry/${request.tag}-secret-server`),
}),
network: (request: any) => record('network', { ...network, request }),
storage: (request: any) => record('storage', { ...storage, request }),
diff --git a/apps/infra/mdeploy/test/stage-entry.test.ts b/apps/infra/mdeploy/test/stage-entry.test.ts
index c35880846..6d777216d 100644
--- a/apps/infra/mdeploy/test/stage-entry.test.ts
+++ b/apps/infra/mdeploy/test/stage-entry.test.ts
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict'
-import { spawnSync } from 'node:child_process'
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
-import { join } from 'node:path'
+import { execFileSync, spawnSync } from 'node:child_process'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
import { tmpdir } from 'node:os'
import test from 'node:test'
import { load } from 'js-yaml'
@@ -9,19 +9,111 @@ import { Lexer, Parser, Evaluator, data } from '@actions/expressions'
const readWorkflow = (name: string): any =>
load(readFileSync(new URL(`../../../../.github/workflows/${name}`, import.meta.url), 'utf8'))
+const readAction = (name: string): any =>
+ load(readFileSync(new URL(`../../../../.github/actions/${name}/action.yml`, import.meta.url), 'utf8'))
const deployment = readWorkflow('mdeploy-all.yml')
const step = (job: any, name: string): any => {
const found = job.steps.find((candidate: any) => candidate.name === name || candidate.id === name)
assert.ok(found, `missing workflow boundary: ${name}`)
return found
}
-const run = (script: string, env: Record<string, string>, cwd?: string) =>
- spawnSync('bash', ['-c', script], {
+const run = (script: string, env: Record<string, string>, cwd?: string, shell = 'bash') =>
+ spawnSync(shell, ['-c', script], {
cwd,
encoding: 'utf8',
env: { ...process.env, ...env },
})
+const gitIn = (cwd: string) => (...args: string[]) =>
+ execFileSync('git', ['-c', 'core.hooksPath=/dev/null', '-c', 'commit.gpgsign=false', ...args], {
+ cwd,
+ encoding: 'utf8',
+ env: { ...process.env, GIT_AUTHOR_NAME: 'Test', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Test', GIT_COMMITTER_EMAIL: '[email protected]' },
+ }).trim()
+
+test('stage release tags and explicitly selected dev PR heads deploy their resolved infrastructure', (t) => {
+ const directory = mkdtempSync(join(tmpdir(), 'infra-source-'))
+ t.after(() => rmSync(directory, { recursive: true, force: true }))
+ const output = join(directory, 'output')
+ const head = 'a'.repeat(40)
+ const candidate = 'e'.repeat(40)
+ for (const [stage, ref, prHead, base, expected, components = 'api+runner'] of [
+ ['dev', '#123', head, 'main', candidate],
+ ['dev', '#123', 'b'.repeat(40), 'main', head],
+ ['dev', '#123', head, 'other', head],
+ ['stage', 'v1.2.3', '', '', candidate],
+ ['stage', 'v0.16.0', '', '', head, 'runner'],
+ ['prod', 'v1.2.3', '', '', head],
+ ]) {
+ writeFileSync(output, '')
+ const result = run(step(deployment.jobs.resolve, 'infra').run, {
+ STAGE: stage!,
+ COMPONENTS: components!,
+ REF: ref!,
+ PR_HEAD: prHead!,
+ PR_BASE: base!,
+ GITHUB_SHA: head,
+ CANDIDATE: candidate,
+ GITHUB_OUTPUT: output,
+ })
+ assert.equal(result.status, 0, result.stderr)
+ assert.equal(readFileSync(output, 'utf8'), `sha=${expected}\n`)
+ }
+ assert.equal(step(deployment.jobs.resolve, 'infra').env.COMPONENTS, '${{ inputs.components }}')
+ for (const job of [deployment.jobs.plan, deployment.jobs.deploy]) {
+ const checkouts = job.steps.filter((item: { uses?: string }) => item.uses?.startsWith('actions/checkout@'))
+ assert.equal(checkouts.length, 1)
+ assert.equal(checkouts[0].with.ref, '${{ needs.resolve.outputs.infra_sha }}')
+ }
+})
+
+test('stage refuses any API-only revision without the worker role before preparing artifacts', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'stage-worker-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const git = gitIn(dir)
+ git('init', '-q')
+ git('commit', '-qm', 'API without Cloud Apps', '--allow-empty')
+ const old = git('rev-parse', 'HEAD')
+ for (const file of ['config/cloud-app-config.ts', 'cloud-app/cloud-app.module.ts', 'cloud-app/cloud-app-worker.ts']) {
+ const dest = join(dir, 'apps/api/src', file)
+ mkdirSync(dirname(dest), { recursive: true })
+ writeFileSync(dest, readFileSync(new URL('../../../api/src/' + file, import.meta.url)))
+ }
+ git('add', '.')
+ git('commit', '-qm', 'API with the Cloud Apps worker')
+ const compatible = git('rev-parse', 'HEAD')
+ git('commit', '-qm', 'Dispatch checkout', '--allow-empty')
+ const current = git('rev-parse', 'HEAD')
+ const output = join(dir, 'out')
+ const select = (sha: string, ref: string) =>
+ run(
+ step(deployment.jobs.resolve, 'infra').run,
+ {
+ STAGE: 'stage',
+ COMPONENTS: 'api',
+ REF: ref,
+ CANDIDATE: sha,
+ GITHUB_SHA: current,
+ PR_HEAD: '',
+ PR_BASE: '',
+ GITHUB_OUTPUT: output,
+ },
+ dir,
+ )
+ for (const ref of ['v0.16.0', old, '#123']) {
+ const denied = select(old, ref)
+ assert.notEqual(denied.status, 0, `incompatible API admitted through ${ref}`)
+ assert.match(denied.stderr + denied.stdout, /CloudAppWorker/)
+ }
+ for (const ref of ['v0.16.1', compatible, '#124']) {
+ writeFileSync(output, '')
+ const admitted = select(compatible, ref)
+ assert.equal(admitted.status, 0, admitted.stderr)
+ assert.equal(readFileSync(output, 'utf8'), `sha=${current}\n`)
+ }
+})
+
test('stage admits SHA, PR and stable tags while prod admission remains', () => {
const directory = mkdtempSync(join(tmpdir(), 'stage-ref-policy-'))
try {
@@ -185,13 +277,103 @@ test('stage PR resolution requires an open, mergeable request and uses its merge
mergeable,
potentialMergeCommit: { oid: merge },
headRefOid: 'a'.repeat(40),
+ baseRefName: 'main',
isCrossRepository: true,
}),
})
assert.equal(result.status === 0, allowed, `${state}/${mergeable}: ${result.stdout}${result.stderr}`)
- assert.equal(readFileSync(output, 'utf8'), allowed ? `sha=${merge}\n` : '')
+ assert.equal(readFileSync(output, 'utf8'), allowed ? `head=${'a'.repeat(40)}\nbase=main\nsha=${merge}\n` : '')
}
} finally {
rmSync(directory, { recursive: true, force: true })
}
})
+
+// The v0.16.1 API and CloudAppWorker use the same image; its build declaration has no Secret Server.
+test('commit API-only rollout plans, publishes and verifies only the API image', (t) => {
+ const directory = mkdtempSync(join(tmpdir(), 'api-only-'))
+ t.after(() => rmSync(directory, { recursive: true, force: true }))
+ const output = join(directory, 'output')
+ const npm = join(directory, 'npm')
+ writeFileSync(
+ npm,
+ `#!/bin/bash
+printf '%s\\n' "$*" >> "$CALLS"
+if [[ "$API_ONLY" == true ]]; then [[ "$*" == *"--artifact api"* ]] || exit 66
+else [[ "$*" != *"--artifact"* ]] || exit 66; fi
+`,
+ { mode: 0o700 },
+ )
+ const env = {
+ PATH: directory + ':' + process.env.PATH,
+ CALLS: join(directory, 'calls'),
+ STAGE: 'stage',
+ TARGET_STAGE: 'stage',
+ SHA: 'a'.repeat(40),
+ IMAGE_TAG: 'a'.repeat(40),
+ BOXLITE_IMAGE_TAG: 'a'.repeat(40),
+ VERSION: '',
+ COMPONENTS: 'api',
+ API_ONLY: 'true',
+ ARTIFACT: 'api',
+ LINE: 'stage tag',
+ GITHUB_OUTPUT: output,
+ GITHUB_STEP_SUMMARY: join(directory, 'summary'),
+ }
+ assert.equal(run(step(deployment.jobs.plan, 'plan').run, env).status, 0)
+ assert.match(readFileSync(output, 'utf8'), /^api=skip$/m)
+ const publish = step(readAction('mbuild').runs, 'Build and upload')
+ const verify = step(readAction('mdeploy').runs, 'Verify the images')
+ assert.match(step(deployment.jobs.plan, 'plan').env.API_ONLY, /inputs.components == 'api'/)
+ assert.match(
+ step(deployment.jobs.plan, 'Build and upload missing images').with.artifact,
+ /inputs.components == 'api'/,
+ )
+ assert.match(publish.env.ARTIFACT, /inputs.artifact/)
+ assert.match(verify.env.API_ONLY, /inputs.components == 'api'/)
+ assert.equal(run(publish.run, env).status, 0)
+ assert.equal(run(verify.run, env).status, 0)
+ assert.equal(readFileSync(env.CALLS, 'utf8').trim().split('\n').length, 3)
+ // The API matrix leg of a full deployment prepares every container.
+ const full = { ...env, API_ONLY: 'false', ARTIFACT: '' }
+ writeFileSync(output, '')
+ for (const script of [step(deployment.jobs.plan, 'plan').run, publish.run, verify.run]) {
+ const result = run(script, full, directory, '/bin/bash')
+ assert.equal(result.status, 0, result.stderr)
+ }
+ assert.match(readFileSync(output, 'utf8'), /^api=skip$/m)
+})
+
+test('a scoped stage Runner uses the build version from the selected commit', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'stage-runner-version-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const git = gitIn(dir)
+ git('init', '-q')
+ writeFileSync(join(dir, 'Cargo.toml'), '[workspace.package]\nversion = "0.16.1"\n')
+ writeFileSync(join(dir, 'tomllib.py'), '') // Inert name collision in the candidate tree.
+ git('add', 'Cargo.toml', 'tomllib.py')
+ git('commit', '-qm', 'candidate')
+ const sha = git('rev-parse', 'HEAD')
+ writeFileSync(join(dir, 'Cargo.toml'), '[workspace.package]\nversion = "0.17.0"\n')
+ const resolve = step(deployment.jobs.resolve, 'runner-version')
+ const address = step(readAction('mdeploy').runs, 'Address what this deploy installs')
+ const output = join(dir, 'output')
+ const env = join(dir, 'env')
+ assert.equal(resolve.env.SHA, '${{ steps.tag.outputs.sha }}')
+ assert.equal(deployment.jobs.resolve.outputs.runner_build_version, '${{ steps.runner-version.outputs.version }}')
+ const deploy = deployment.jobs.deploy.steps.find((s: any) => s.uses === './.github/actions/mdeploy')
+ assert.equal(deploy.with['runner-build-version'], '${{ needs.resolve.outputs.runner_build_version }}')
+ assert.equal(address.env.RUNNER_BUILD_VERSION, '${{ inputs.runner-build-version }}')
+ const resolved = run(resolve.run, { SHA: sha, GITHUB_OUTPUT: output }, dir)
+ assert.equal(resolved.status, 0, resolved.stderr)
+ const version = readFileSync(output, 'utf8').trim().split('=')[1]!
+ for (const components of ['runner', 'api+runner']) {
+ writeFileSync(env, '')
+ const result = run(address.run, {
+ SHA: sha, COMPONENTS: components, VERSION: '', RUNNER_BUILD_VERSION: version,
+ IMAGE_TAG: sha, RELEASE_PINS: '', GITHUB_ENV: env,
+ }, dir)
+ assert.equal(result.status, 0, result.stderr)
+ assert.match(readFileSync(env, 'utf8'), /^VERSION=0\.16\.1$/m)
+ }
+})
diff --git a/apps/infra/mdeploy/test/support/discovery-clock.cjs b/apps/infra/mdeploy/test/support/discovery-clock.cjs
new file mode 100644
index 000000000..d4c64abf7
--- /dev/null
+++ b/apps/infra/mdeploy/test/support/discovery-clock.cjs
@@ -0,0 +1,16 @@
+// Advance the discovery process's retry clock while its HTTPS requests still cross a real socket.
+const timers = require('node:timers/promises')
+const { syncBuiltinESMExports } = require('node:module')
+let elapsed = 0
+timers.setTimeout = async (milliseconds) => {
+ elapsed += milliseconds
+ if (elapsed > 310_000) throw new Error('discovery exceeded its readiness budget')
+}
+syncBuiltinESMExports()
+Object.defineProperty(performance, 'now', { value: () => elapsed })
+const realFetch = globalThis.fetch
+globalThis.fetch = (url, options) =>
+ realFetch(url, {
+ ...options,
+ headers: { ...options.headers, 'x-test-elapsed-ms': String(elapsed) },
+ })
diff --git a/apps/infra/mdeploy/test/support/discovery-gcloud.cjs b/apps/infra/mdeploy/test/support/discovery-gcloud.cjs
new file mode 100644
index 000000000..28f53aa82
--- /dev/null
+++ b/apps/infra/mdeploy/test/support/discovery-gcloud.cjs
@@ -0,0 +1,19 @@
+#!/usr/bin/env node
+const fs = require('node:fs')
+const [group, resource, action, vmName, ...options] = process.argv.slice(2)
+if (
+ group !== 'compute' ||
+ resource !== 'instances' ||
+ action !== 'describe' ||
+ !options.includes('--project=project') ||
+ !options.includes('--zone=us-east5-a') ||
+ !options.includes('--format=value(id)')
+)
+ process.exit(2)
+fs.appendFileSync(process.env.TEST_GCE_CALLS, vmName + '\n')
+const value = JSON.parse(fs.readFileSync(process.env.TEST_GCE_INSTANCES, 'utf8'))[vmName]
+if (value === undefined) {
+ console.error('synthetic-gcloud-error')
+ process.exit(1)
+}
+process.stdout.write(value + '\n')
diff --git a/apps/infra/mdeploy/test/support/gcp-runner-stack.ts b/apps/infra/mdeploy/test/support/gcp-runner-stack.ts
new file mode 100644
index 000000000..919b20a2b
--- /dev/null
+++ b/apps/infra/mdeploy/test/support/gcp-runner-stack.ts
@@ -0,0 +1,77 @@
+import type { TestContext } from 'node:test'
+import type { RunnerRequest } from '../../stack/runners.ts'
+import { gcpRunnerProvider } from '../../stack/providers/gcp/runners.ts'
+import { resolveRunnerBinary } from '../../stack/runner-binary.ts'
+
+export function mockRunnerStack(t: TestContext) {
+ const output = (value: any): any => ({ value, apply: (fn: (value: any) => any) => output(fn(value)) })
+ const secretInputs = new WeakSet<object>()
+ const resources = new Map<string, { args: any; options: any; resource: any }>()
+ class Resource {
+ [key: string]: any
+ constructor(name: string, args: any, options: any = {}) {
+ resources.set(name, { args, options, resource: this })
+ Object.assign(this, args, { id: output(name), name: output(name) })
+ if (args.metadataStartupScript) this.instanceId = output(name === 'Runner' ? '12345' : '67890')
+ if (name === 'SecretServerRunnerRegistry') {
+ const slots: { name: string }[] = JSON.parse(args.stdin.value)
+ const entries = slots.map(({ name }, index) => [index === 0 ? '12345' : String(67890 + index - 1), name])
+ this.stdout = output(JSON.stringify({ gcp_iit: Object.fromEntries(entries) }))
+ }
+ }
+ }
+ const constructors = new Proxy({}, { get: () => Resource })
+ const globals = {
+ gcp: new Proxy({}, { get: () => constructors }),
+ command: { local: constructors },
+ $jsonStringify: (input: unknown) => output(JSON.stringify(input, (_, v) => v?.value ?? v)),
+ $app: { name: 'boxlite-app', stage: 'dev' },
+ $util: {
+ output,
+ secret: (value: any) => {
+ const input = value?.apply ? value : output(value)
+ secretInputs.add(input)
+ return input
+ },
+ },
+ $resolve: (values: any[]) => output(values.map((value) => value?.value ?? value)),
+ }
+ for (const [key, value] of Object.entries(globals)) {
+ const previous = Object.getOwnPropertyDescriptor(globalThis, key)
+ Object.defineProperty(globalThis, key, { configurable: true, value })
+ t.after(() =>
+ previous ? Object.defineProperty(globalThis, key, previous) : Reflect.deleteProperty(globalThis, key),
+ )
+ }
+ const provider = gcpRunnerProvider({
+ project: 'project',
+ zone: 'us-east5-a',
+ volumePrefix: 'boxlite-volume',
+ artifactsBucket: 'artifacts',
+ adminApiKey: 'admin',
+ regionId: 'region',
+ dependsOn: [],
+ placement: { cloud: 'gcp', subnetwork: output('subnet'), serviceAccount: output('[email protected]') } as any,
+ })
+ const requestFor = (count: number): RunnerRequest => ({
+ size: 'small',
+ rootDiskGb: 100,
+ nestedVirtualization: true,
+ fleet: Array.from({ length: count }, (_, index) => ({
+ slot: {
+ resourceName: index ? `Runner-runner-${index + 1}` : 'Runner',
+ nameTag: `boxlite-app-dev-runner${index ? `-${index + 1}` : ''}`,
+ controlPlaneRunnerName: index ? `runner-${index + 1}` : 'default',
+ },
+ token: 'test-token',
+ })),
+ binary: resolveRunnerBinary({ environment: {}, configRoot: '.', readVersion: () => '0.10.8' }),
+ apiUrl: 'https://api.dev.example.com',
+ otlpUrl: 'http://otel:4317',
+ registryProxyHost: null,
+ checkpointBucket: null,
+ environment: {},
+ secrets: {},
+ })
+ return { output, globals, resources, provider, requestFor, secretInputs }
+}
diff --git a/apps/infra/mstage.env.json b/apps/infra/mstage.env.json
index 6e3b3503b..aef11c150 100644
--- a/apps/infra/mstage.env.json
+++ b/apps/infra/mstage.env.json
@@ -18,6 +18,12 @@
"registry-proxy": {
"dockerfile": "apps/image-service/Dockerfile",
"context": "."
+ },
+ "secret-server": {
+ "dockerfile": "apps/secret-server/Dockerfile",
+ "context": ".",
+ "deployCloud": "gcp",
+ "deployStages": ["dev", "stage", "prod"]
}
},
"audit": {
@@ -90,6 +96,8 @@
"POSTHOG_HOST",
"INCIDENT_IO_ALERT_SOURCE_CONFIG_ID",
"INCIDENT_IO_HEARTBEAT_ID",
+ "SECRET_SERVER_INCIDENT_CHANNEL",
+ "SECRET_SERVER_FETCH_LIMIT",
"STATUS_SYNC_DEDUP_PREFIX"
]
},
@@ -123,6 +131,7 @@
"DB_POOL_MAX",
"CHECKPOINTS_ENABLED",
"MEMORY_CHECKPOINTS_ENABLED",
+ "SECRET_SERVER_ENABLED",
"FILESTORE_INSTANCES",
"BOXLITE_SYSTEM_SOURCE_REGISTRY_PASSWORD",
"GHCR_USERNAME",
diff --git a/apps/infra/scripts/resolve-gcp-runner-registry.mjs b/apps/infra/scripts/resolve-gcp-runner-registry.mjs
new file mode 100644
index 000000000..cfb672ba5
--- /dev/null
+++ b/apps/infra/scripts/resolve-gcp-runner-registry.mjs
@@ -0,0 +1,129 @@
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { setTimeout as sleep } from 'node:timers/promises'
+import { text } from 'node:stream/consumers'
+
+class RegistryError extends Error {}
+
+const execFileAsync = promisify(execFile)
+
+async function waitForApi(api) {
+ const endpoint = new URL('/api/health', api)
+ const deadline = performance.now() + 300_000
+ for (;;) {
+ const remaining = Math.ceil(deadline - performance.now())
+ if (remaining <= 0) break
+ try {
+ const response = await fetch(endpoint, {
+ redirect: 'manual',
+ signal: AbortSignal.timeout(Math.min(5000, remaining)),
+ })
+ await response.body?.cancel()
+ if (response.ok && performance.now() < deadline) return
+ } catch {
+ // A cold public endpoint can refuse connections before serving its first revision.
+ }
+ await sleep(Math.max(0, Math.min(5000, deadline - performance.now())))
+ }
+ throw new RegistryError('Public API /api/health not ready after 5 minutes')
+}
+
+async function currentInstanceId(project, zone, vmName) {
+ let id
+ try {
+ const { stdout } = await execFileAsync(
+ 'gcloud',
+ ['compute', 'instances', 'describe', vmName, `--project=${project}`, `--zone=${zone}`, '--format=value(id)'],
+ { timeout: 30_000 },
+ )
+ id = stdout.trim()
+ } catch {
+ throw new RegistryError(`GCE lookup failed for VM ${vmName}`)
+ }
+ if (!/^[1-9][0-9]{0,19}$/.test(id)) throw new RegistryError(`Invalid GCE instance ID for VM ${vmName}`)
+ return id
+}
+
+async function registeredId(endpoint, { name, token }) {
+ for (let attempt = 1; attempt <= 6; attempt++) {
+ let response
+ try {
+ response = await fetch(endpoint, {
+ headers: { authorization: `Bearer ${token}` },
+ redirect: 'manual',
+ signal: AbortSignal.timeout(5000),
+ })
+ } catch {
+ // The API can still be starting on the first deployment.
+ }
+ if (response?.status === 200) {
+ // The full response contains the Runner API key. Only the UUID leaves this process.
+ let runner
+ try {
+ runner = await response.json()
+ } catch {
+ throw new RegistryError(`Invalid identity response for Runner ${name}`)
+ }
+ if (
+ runner?.name !== name ||
+ runner.apiVersion !== '2' ||
+ typeof runner.id !== 'string' ||
+ !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(runner.id)
+ ) {
+ throw new RegistryError(`Unexpected registered identity for Runner ${name}`)
+ }
+ return runner.id.toLowerCase()
+ }
+ const status = response?.status
+ await response?.body?.cancel()
+ if (attempt === 6 || (status && status !== 401 && status !== 429 && status < 500)) {
+ throw new RegistryError(`Cannot identify Runner ${name} (${status ?? 'connection failed'})`)
+ }
+ await sleep(attempt * 1000)
+ }
+}
+
+async function main() {
+ const api = new URL(process.env.API_URL)
+ if (api.protocol !== 'https:' || api.username || api.password || api.search || api.hash || api.pathname !== '/') {
+ throw new RegistryError('Expected an HTTPS API origin')
+ }
+ const endpoint = new URL('/api/runners/me', api)
+ const fleet = JSON.parse(await text(process.stdin))
+ if (!Array.isArray(fleet) || !fleet.length) throw new RegistryError('Runner fleet is empty')
+
+ const { GCP_PROJECT: project, GCP_ZONE: zone } = process.env
+ if (!project || !zone) throw new RegistryError('GCE project and zone are required')
+ await waitForApi(api)
+
+ const machines = new Map()
+ const ids = new Set()
+ for (const host of fleet) {
+ if (
+ typeof host?.vmName !== 'string' ||
+ !/^[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?$/.test(host.vmName) ||
+ typeof host.name !== 'string' ||
+ !host.name ||
+ /[\x00-\x1f\x7f]/.test(host.name) ||
+ typeof host.token !== 'string' ||
+ !host.token
+ ) {
+ throw new RegistryError('Invalid GCE Runner assignment')
+ }
+ const instanceId = await currentInstanceId(project, zone, host.vmName)
+ if (machines.has(instanceId)) throw new RegistryError(`Duplicate GCE instance for Runner ${host.name}`)
+ const id = await registeredId(endpoint, host)
+ if (ids.has(id)) throw new RegistryError(`Duplicate registered UUID for Runner ${host.name}`)
+ ids.add(id)
+ machines.set(instanceId, id)
+ }
+ process.stdout.write(JSON.stringify({ gcp_iit: Object.fromEntries(machines) }))
+}
+
+main().catch((error) => {
+ // Parse errors can quote input containing credentials.
+ console.error(
+ error instanceof RegistryError ? error.message : 'Could not read the GCP Runner registry inputs or API reply',
+ )
+ process.exitCode = 1
+})
diff --git a/apps/secret-server/README.md b/apps/secret-server/README.md
index 110280b4e..219f7aa1e 100644
--- a/apps/secret-server/README.md
+++ b/apps/secret-server/README.md
@@ -6,7 +6,8 @@ The internal encryption package protects secret values and routing policy with p
This Go module runs Secret Server with database initialization, a migration
command, authenticated secret transfer and metadata endpoints, and an
-authenticated fetch endpoint.
+authenticated fetch endpoint. See the
+[mdeploy runbook](../infra/mdeploy/README.md#gcp-secret-server) for GCP deployment and verification.
The existing API encryption service and stored values remain unchanged.
## Server skeleton
@@ -15,8 +16,10 @@ Set `SECRET_SERVER_ROLE` to `write`, `fetch`, or `all`; set `ENVIRONMENT`,
`DATABASE_URL`, `SECRET_MASTER_KEY_ID`, `SECRET_MASTER_KEY_BASE64`, and
`SECRET_SERVER_AUTH_MODE`. Google mode requires `SECRET_SERVER_AUDIENCE` and,
for write or all roles, `SECRET_SERVER_ALLOWED_CALLERS`. Dev mode requires
-`SECRET_SERVER_DEV_TOKEN` and is limited to local and dev environments. The
-environment key provider is rejected in production.
+`SECRET_SERVER_DEV_TOKEN` and is limited to local and dev environments.
+
+Production uses Google authentication. Both production roles load the same numbered
+Secret Manager version as `SECRET_MASTER_KEY_BASE64` and verify the database canary before serving.
The write route group validates Google ID tokens and permits only verified emails
on the allowlist. The fetch route checks Runner proof in `fetch` and `all` roles.
@@ -143,7 +146,7 @@ resolve to a nonzero TCP port so the service does not silently select one.
## Calling the package
-The future application configuration layer reads `SECRET_MASTER_KEY_ID` and
+The server reads `SECRET_MASTER_KEY_ID` and
`SECRET_MASTER_KEY_BASE64`, then passes both strings to `NewEnvKeyProvider`.
The package does not read process environment itself.
@@ -170,7 +173,7 @@ The provider requires a canonical standard Base64 encoding of exactly 32 random
key bytes. IDs start with `env:`, followed by ASCII letters, digits, `.`, `_`, or
`-`, with a maximum total length of 128 bytes. There is no default key.
Construct the provider and cipher before serving requests; their zero values are
-not configured instances. Configure one master key for development/staging only.
+not configured instances. Configure one persistent master key per environment.
`Encrypt` creates a new 32-byte DEK on every call, even for identical inputs.
`Decrypt` unwraps the saved DEK and authenticates the value before returning it.
@@ -311,8 +314,7 @@ Invalid attestation configuration prevents startup before the listener opens.
`exp`. This package checks `iss`, `iat` at most 60 seconds ahead, `email`
and `email_verified`, the Compute Engine `project_id`, and that
`instance_id` is in the registry's `gcp_iit` section.
-- **Registry.** JSON `{mode: {machine_id: runner_id}}`, written by hand for
- staging. With `gcp_iit` enabled, an unset or blank registry fails startup.
+- **Registry.** JSON `{mode: {machine_id: runner_id}}`. GCP mdeploy generates the instance-ID to Runner-UUID map on full deployment. With `gcp_iit` enabled, an unset or blank registry fails startup.
An explicit `{}` allows startup and logs a warning that no GCP runners can
authenticate.
@@ -326,7 +328,7 @@ Invalid attestation configuration prevents startup before the listener opens.
verifier error details.
Known limitations: a captured token can be replayed until it expires, about
-an hour; the zone is not checked; the registry is written by hand.
+an hour; the zone is not checked.
## Verification
diff --git a/apps/secret-server/cmd/secret-server/main_test.go b/apps/secret-server/cmd/secret-server/main_test.go
index a060ef2de..bbbe386e8 100644
--- a/apps/secret-server/cmd/secret-server/main_test.go
+++ b/apps/secret-server/cmd/secret-server/main_test.go
@@ -4,7 +4,6 @@ import (
"context"
"encoding/base64"
"errors"
- "fmt"
"net"
"net/http"
"net/url"
@@ -52,45 +51,36 @@ func TestWrongKeyDoesNotStartServer(t *testing.T) {
if err := database.Initialize(ctx, pool, cipher); err != nil {
t.Fatal(err)
}
- for name, value := range map[string]string{"DATABASE_URL": databaseURL, "ENVIRONMENT": "local", "SECRET_SERVER_ROLE": "write", "SECRET_SERVER_AUTH_MODE": "dev", "SECRET_SERVER_DEV_TOKEN": "integration-token", "SECRET_MASTER_KEY_ID": "env:test", "SECRET_MASTER_KEY_BASE64": originalKey, "PORT": "8080", "SHUTDOWN_TIMEOUT_SEC": "5"} {
+ for name, value := range map[string]string{
+ "DATABASE_URL": databaseURL,
+ "SECRET_MASTER_KEY_ID": "env:test",
+ "SECRET_MASTER_KEY_BASE64": originalKey,
+ "SECRET_SERVER_ROLE": "write",
+ "PORT": "8080",
+ "SHUTDOWN_TIMEOUT_SEC": "5",
+ "ENVIRONMENT": "production",
+ "SECRET_SERVER_AUTH_MODE": "google",
+ "SECRET_SERVER_AUDIENCE": "https://secrets.example.invalid",
+ "SECRET_SERVER_ALLOWED_CALLERS": "[email protected]",
+ "SECRET_SERVER_ATTESTORS": "gcp_iit",
+ "SECRET_SERVER_GCP_PROJECT": "test-project",
+ "SECRET_SERVER_RUNNER_SERVICE_ACCOUNT": "[email protected]",
+ "SECRET_SERVER_RUNNER_REGISTRY": "{}",
+ "SECRET_SERVER_INTROSPECTION_URL": "https://api.example.invalid/internal/v1/credentials/introspect",
+ } {
t.Setenv(name, value)
}
- t.Run("original key restarts against existing canary", func(t *testing.T) {
- runCtx, stop := context.WithCancel(ctx)
- defer stop()
- probe := make(chan error, 1)
- err := runWithListener(runCtx, nil, func(network, _ string) (net.Listener, error) {
- listener, err := net.Listen(network, "127.0.0.1:0")
- if err != nil {
- return nil, err
+ for _, role := range []string{"write", "fetch"} {
+ t.Run(role, func(t *testing.T) {
+ t.Setenv("SECRET_SERVER_ROLE", role)
+ server := startRuntime(t, ctx)
+ address := server.awaitAddress(t, ctx)
+ if got := runtimeStatus(t, address, "/ready", ""); got != http.StatusOK {
+ t.Fatalf("production %s /ready = %d", role, got)
}
- go func() {
- defer stop()
- client := &http.Client{Timeout: 3 * time.Second}
- response, err := client.Get("http://" + listener.Addr().String() + "/ready")
- if err == nil {
- response.Body.Close()
- if response.StatusCode != http.StatusOK {
- err = fmt.Errorf("/ready returned %d", response.StatusCode)
- }
- }
- probe <- err
- }()
- return listener, nil
})
- if err != nil {
- t.Fatalf("restart with original key: %v", err)
- }
- select {
- case err := <-probe:
- if err != nil {
- t.Fatal(err)
- }
- default:
- t.Fatal("restart did not serve readiness")
- }
- })
+ }
t.Run("different valid key never listens", func(t *testing.T) {
wrong := make([]byte, 32)
diff --git a/apps/secret-server/internal/encryption/env.go b/apps/secret-server/internal/encryption/env.go
index cb37d3ffa..dfcff4849 100644
--- a/apps/secret-server/internal/encryption/env.go
+++ b/apps/secret-server/internal/encryption/env.go
@@ -8,7 +8,7 @@ import (
// EnvKeyProvider is configured once from SECRET_MASTER_KEY_ID and
// SECRET_MASTER_KEY_BASE64 by the application, not through ambient reads here.
-// It is intended for development/staging; production key custody belongs in KMS.
+// All revisions reading one database must use the same key ID and key material.
type EnvKeyProvider struct {
keyID string
key [32]byte
diff --git a/apps/secret-server/internal/server/config.go b/apps/secret-server/internal/server/config.go
index 50bc8fd1f..375b0f908 100644
--- a/apps/secret-server/internal/server/config.go
+++ b/apps/secret-server/internal/server/config.go
@@ -55,9 +55,6 @@ func LoadConfig() (Config, error) {
if c.Environment != "local" && c.Environment != "dev" && c.Environment != "staging" && c.Environment != "production" {
return c, errors.New("invalid ENVIRONMENT")
}
- if c.Environment == "production" {
- return c, errors.New("SECRET_MASTER_KEY_BASE64 environment provider is not permitted for ENVIRONMENT production")
- }
switch c.AuthMode {
case "dev":
if c.Environment != "local" && c.Environment != "dev" {
diff --git a/apps/secret-server/internal/server/config_test.go b/apps/secret-server/internal/server/config_test.go
index 6acfe6307..029d7d8a6 100644
--- a/apps/secret-server/internal/server/config_test.go
+++ b/apps/secret-server/internal/server/config_test.go
@@ -22,13 +22,18 @@ func TestLoadConfig(t *testing.T) {
}
}
-func TestConfigRejectsDevInStagingWithoutLeakingValues(t *testing.T) {
+func TestConfigRejectsDevAuthOutsideDevelopmentWithoutLeakingValues(t *testing.T) {
for name, value := range map[string]string{"SECRET_SERVER_ROLE": "write", "ENVIRONMENT": "staging", "DATABASE_URL": "postgres://secret-marker/db", "SECRET_MASTER_KEY_ID": "env:test", "SECRET_MASTER_KEY_BASE64": "secret-marker", "SECRET_SERVER_AUTH_MODE": "dev", "SECRET_SERVER_DEV_TOKEN": "secret-marker", "SECRET_SERVER_AUDIENCE": "", "SECRET_SERVER_ALLOWED_CALLERS": "", "PORT": "", "SHUTDOWN_TIMEOUT_SEC": ""} {
t.Setenv(name, value)
}
- _, err := LoadConfig()
- if err == nil || !strings.Contains(err.Error(), "SECRET_SERVER_AUTH_MODE") || strings.Contains(err.Error(), "secret-marker") {
- t.Fatalf("unexpected error: %v", err)
+ for _, environment := range []string{"staging", "production"} {
+ t.Run(environment, func(t *testing.T) {
+ t.Setenv("ENVIRONMENT", environment)
+ _, err := LoadConfig()
+ if err == nil || !strings.Contains(err.Error(), "SECRET_SERVER_AUTH_MODE") || strings.Contains(err.Error(), "secret-marker") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ })
}
}