From 2e23bb8e75088f02b3900e43c5f10ef1eb0f92ab Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:36:10 +0100 Subject: [PATCH 01/91] Test: the loader returns each stack's environments Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/stacks.test.ts | 92 +++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/packages/lib/src/stacks.test.ts b/packages/lib/src/stacks.test.ts index cf9d390d..bf6e839c 100644 --- a/packages/lib/src/stacks.test.ts +++ b/packages/lib/src/stacks.test.ts @@ -398,3 +398,95 @@ test("the package's index exports the loader and no longer the special service n assert.equal(typeof index.loadStacks, 'function'); assert.equal('APP_SERVICE' in index, false); }); + +// --- environments -------------------------------------------------------------- + +/** The environments of the one stack of a repo whose stack/ holds `files`. */ +const environmentsOf = async (files: Tree) => { + const repo = await load({ stack: { 'compose.yaml': compose(), ...files }, apps: { shop: dockerfile } }); + return repo.stacks[0]?.environments ?? []; +}; + +test("a stack's environments are its `.yaml` files but the compose files, by name, parsed into host, hostname, env and secrets", async () => { + const environments = await environmentsOf({ + 'staging.yaml': 'host: 192.0.2.2\nenv:\n MODE: staging\n RETRIES: 3\n DEBUG: true\n', + 'production.yaml': + 'host: 192.0.2.1\nhostname: shop.example.com\nenv:\n MODE: production\nsecrets:\n TOKEN: op://acme/shop/token\n', + 'compose.dev.yaml': 'services: {}\n', + 'PLEXUS.md': marker(), + 'notes.txt': 'x', + }); + assert.deepEqual(environments, [ + { + name: 'production', + file: '/work/shop/stack/production.yaml', + host: '192.0.2.1', + hostname: 'shop.example.com', + env: { MODE: 'production' }, + secrets: { TOKEN: 'op://acme/shop/token' }, + problems: [], + }, + { + name: 'staging', + file: '/work/shop/stack/staging.yaml', + host: '192.0.2.2', + env: { MODE: 'staging', RETRIES: '3', DEBUG: 'true' }, + secrets: {}, + problems: [], + }, + ]); +}); + +test('a stack without environment files has no environments, and the loader reports no problem', async () => { + const repo = await load({ stack: { 'compose.yaml': compose() }, apps: { shop: dockerfile } }); + assert.deepEqual(repo.stacks[0]?.environments, []); + assert.deepEqual(repo.problems, []); +}); + +test('each stack of several has the environments of its own directory', async () => { + const repo = await load({ + apps: { shop: dockerfile }, + stacks: { + a: { 'compose.yaml': compose(), 'staging.yaml': 'host: 192.0.2.1\n' }, + b: { 'compose.yaml': compose('postgres:16'), 'production.yaml': 'host: 192.0.2.2\n' }, + }, + }); + assert.deepEqual( + repo.stacks.map((s) => s.environments.map((e) => e.name)), + [['staging'], ['production']], + ); +}); + +test('an environment file that cannot be used says why in its own problems, and is still returned', async () => { + const cases: [string, string, RegExp][] = [ + ['staging', 'host: 192.0.2.1\nport: 1\n', /unknown key `port`/], + ['staging', 'hostname: shop.example.com\n', /no `host`/], + ['staging', 'host: 192.0.2.1\nsecrets:\n TOKEN: plain\n', /`TOKEN`.*op:\/\//], + ['staging', 'host: 192.0.2.1\nenv:\n LIST: [a]\n', /`LIST`.*plain value/], + ['staging', 'host: 192.0.2.1\nenv: [a]\n', /`env`.*map/], + ['staging', 'host: 192.0.2.1\nsecrets: x\n', /`secrets`.*map/], + ['staging', 'host: 3\n', /`host`.*string/], + ['staging', 'host: 192.0.2.1\nhostname: 3\n', /`hostname`.*string/], + ['staging', '- a\n', /map/], + ['staging', 'host: [\n', /not valid YAML/], + ['Staging', 'host: 192.0.2.1\n', /one lowercase word/], + ['pre-prod', 'host: 192.0.2.1\n', /one lowercase word/], + ['a.b', 'host: 192.0.2.1\n', /one lowercase word/], + ]; + for (const [name, text, problem] of cases) { + const [environment, ...rest] = await environmentsOf({ [`${name}.yaml`]: text }); + assert.equal(rest.length, 0, text); + assert.equal(environment?.name, name, text); + assert.equal(environment?.problems.length, 1, `${text}: ${environment?.problems.join('; ')}`); + assert.match(environment?.problems[0] ?? '', problem, text); + assert.match(environment?.problems[0] ?? '', new RegExp(`${name.replace('.', '\\.')}\\.yaml`)); + } +}); + +test('an empty environment file lacks its host and nothing else', async () => { + const [environment] = await environmentsOf({ 'staging.yaml': '' }); + assert.deepEqual(environment?.env, {}); + assert.deepEqual(environment?.secrets, {}); + assert.equal(environment?.host, undefined); + assert.equal(environment?.problems.length, 1); +}); From d44bf280ddc8c7009d1ff344bfeab6e063e58652 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:37:33 +0100 Subject: [PATCH 02/91] The loader returns each stack's environments Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/environments.ts | 109 +++++++++++++++++++++++++++++++ packages/lib/src/index.ts | 4 ++ packages/lib/src/stacks.ts | 9 ++- 3 files changed, 120 insertions(+), 2 deletions(-) create mode 100644 packages/lib/src/environments.ts diff --git a/packages/lib/src/environments.ts b/packages/lib/src/environments.ts new file mode 100644 index 00000000..1a7d8f1a --- /dev/null +++ b/packages/lib/src/environments.ts @@ -0,0 +1,109 @@ +// The environments of a stack, and the variables the platform supplies: what +// the loader (stacks.ts) reads of a stack's directory beyond its compose file, +// and the one list the checks and the deploy hold a compose file against. +// +// An environment is one stack on one host with its full configuration, and its +// configuration is a file in the stack's directory named after it: +// `production.yaml` is the environment `production`. Every `.yaml` of the +// directory is one, but the compose files (`compose.yaml`, `compose.dev.yaml`). +// A name is one lowercase word, letters only, and no name has a meaning: no +// code compares one with a literal. The file is a YAML map with exactly four +// keys: +// host the machine's address, a non-empty string; required +// hostname the public name the proxy serves, a non-empty string; optional, +// and without it the environment gets no loopback port and no route +// env a map of names to plain values (string, number or boolean, read +// as the string compose would see); absent reads as empty +// secrets a map of names to `op://` pointers, strings; absent reads as empty +// `readEnvironments` returns one `Environment` per file in the order of their +// names, and never throws: whatever makes a file unusable is a line of its +// `problems` that names the file, and the values it could read are returned +// all the same, so that every problem is found in one run. +import { join } from 'node:path'; +import { parse } from 'yaml'; +import { isMapping } from './compose.ts'; +import type { Context } from './context.ts'; + +/** One stack on one host, as its file states it. */ +export interface Environment { + /** The file's name without `.yaml`. */ + name: string; + /** The file, absolute. */ + file: string; + host?: string; + hostname?: string; + env: Record; + /** Names to `op://` pointers. */ + secrets: Record; + /** What makes the file unusable, one line each, each naming the file. */ + problems: string[]; +} + +/** The files of a stack's directory that hold no environment. */ +const COMPOSE_FILES = new Set(['compose.yaml', 'compose.dev.yaml']); + +/** What an environment's name is: one lowercase word. */ +const ENVIRONMENT_NAME = /^[a-z]+$/; + +const KEYS = ['host', 'hostname', 'env', 'secrets']; + +/** The environments of the stack whose directory is `dir`, by name. */ +export async function readEnvironments(ctx: Context, dir: string): Promise { + const entries = await ctx.readDir(dir).catch(() => []); + const names = entries + .filter((e) => !e.directory && e.name.endsWith('.yaml') && !COMPOSE_FILES.has(e.name)) + .map((e) => e.name.slice(0, -'.yaml'.length)) + .sort(); + const environments: Environment[] = []; + for (const name of names) environments.push(await readEnvironment(ctx, dir, name)); + return environments; +} + +async function readEnvironment(ctx: Context, dir: string, name: string): Promise { + const file = join(dir, `${name}.yaml`); + const label = `${name}.yaml`; + const environment: Environment = { name, file, env: {}, secrets: {}, problems: [] }; + const problem = (text: string) => environment.problems.push(`${label}: ${text}`); + if (!ENVIRONMENT_NAME.test(name)) + problem(`\`${name}\` is no environment name; a name is one lowercase word (letters only, no \`-\`)`); + let doc: unknown; + try { + doc = parse(await ctx.readFile(file)); + } catch (error) { + problem(`not valid YAML: ${(error as Error).message.split('\n')[0]?.replace(/:$/, '')}`); + return environment; + } + if (doc === null || doc === undefined) doc = {}; + if (!isMapping(doc)) { + problem('is not a map of `host`, `hostname`, `env` and `secrets`'); + return environment; + } + for (const key of Object.keys(doc).filter((k) => !KEYS.includes(k))) + problem(`unknown key \`${key}\`; the keys are ${KEYS.map((k) => `\`${k}\``).join(', ')}`); + for (const key of ['host', 'hostname'] as const) { + const value = doc[key]; + if (value === undefined) continue; + if (typeof value === 'string' && value !== '') environment[key] = value; + else problem(`\`${key}\` is not a non-empty string`); + } + if (environment.host === undefined && doc.host === undefined) problem("has no `host`, the machine's address"); + for (const [key, into] of [ + ['env', environment.env], + ['secrets', environment.secrets], + ] as const) { + const map = doc[key]; + if (map === undefined || map === null) continue; + if (!isMapping(map)) { + problem(`\`${key}\` is not a map of names to values`); + continue; + } + for (const [variable, value] of Object.entries(map)) { + if (key === 'env') { + if (['string', 'number', 'boolean'].includes(typeof value)) into[variable] = String(value); + else problem(`\`env\` \`${variable}\` is not a plain value (a string, a number or a boolean)`); + } else if (typeof value === 'string' && value.startsWith('op://')) into[variable] = value; + else problem(`\`secrets\` \`${variable}\` is no \`op://\` pointer`); + } + } + return environment; +} diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 7cd5da7f..345c709d 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -77,6 +77,10 @@ export { } from './doctor.ts'; export { body, describe, type Plan, run, type Step, write } from './effects.ts'; export { envFlag } from './envFlag.ts'; +export { + type Environment, + readEnvironments, +} from './environments.ts'; export { frontmatterField, setFrontmatterField } from './frontmatter.ts'; export { type DirEntry, diff --git a/packages/lib/src/stacks.ts b/packages/lib/src/stacks.ts index 56e8bccb..bda66a4f 100644 --- a/packages/lib/src/stacks.ts +++ b/packages/lib/src/stacks.ts @@ -7,8 +7,9 @@ // has the repo's name, or several at `stacks//compose.yaml`, each named // after its directory. No compose file of a stack lives at the repo's root or // inside an app. A stack's directory may hold `compose.dev.yaml`, which is -// reported (`dev`) and never read, and a `PLEXUS.md`, whose frontmatter is -// returned as `marker`. An app is a directory under `apps/` that holds a +// reported (`dev`) and never read, a `PLEXUS.md`, whose frontmatter is +// returned as `marker`, and one `.yaml` per environment, returned as +// `environments` (environments.ts states the file's shape). An app is a directory under `apps/` that holds a // `Dockerfile`. // // The repo's name is the `repo` key (REPO_KEY) of its root `PLEXUS.md`, a non-empty @@ -54,6 +55,7 @@ import { join, relative, resolve } from 'node:path'; import { type Compose, parseCompose } from './compose.ts'; import type { Context } from './context.ts'; +import { type Environment, readEnvironments } from './environments.ts'; import { MARKER_FILE, splitFrontmatter } from './marker.ts'; import { APPS_DIR } from './model.ts'; import { isDirectory } from './overview.ts'; @@ -93,6 +95,8 @@ export interface Stack { apps: StackApp[]; /** The services that run an image pinned literally, in the file's order. */ pinned: StackPin[]; + /** Its environments, by name: the `.yaml` files of the directory (environments.ts). */ + environments: Environment[]; } /** What a repo's stacks are and what is wrong with how they are laid out. */ @@ -228,6 +232,7 @@ async function stackAt( dev: entries.has('compose.dev.yaml'), ...(marker === undefined ? {} : { marker }), ...used, + environments: await readEnvironments(ctx, dir), }; return { stack, images, hasCompose: text !== undefined }; } From 4472d382abbb40dedb8bae8768cf48a9104960ac Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:38:13 +0100 Subject: [PATCH 03/91] Test: doctor holds environment files to each other and to the compose file Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.test.ts | 121 ++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 6758d3b1..d7587fca 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -79,6 +79,7 @@ const loaded = (over: Partial = {}): Stack => ({ dev: false, apps: [{ service: 'web', app: 'shop' }], pinned: [], + environments: [], ...over, }); const stacksOf = (over: Partial = {}): RepoStacks => ({ @@ -156,6 +157,7 @@ const stack = (profile: string | undefined, over: Partial = {}, devi repoApps: ['shop'], registries: ['ghcr.io/acme'], problems: [], + environments: [], packageJsons: { shop: { packageJson: { scripts: { seed: 'tsx seed.ts' } } } }, ...over, }; @@ -2338,3 +2340,122 @@ test('a root marker that lists no templates is checked for keys where a nested m { problem: UNKNOWN_ROOT('stray') }, ]); }); + +// --- environment files --------------------------------------------------------- + +const FROM_ENV = ` web: + image: ghcr.io/acme/site:\${PLEXUS_TAG:?set} +${SITE_SERVICES} ports: ["127.0.0.1:\${PLEXUS_LOOPBACK_PORT:?set}:3000"] + healthcheck: { test: [CMD, "true"] } + environment: + MODE: \${MODE} + SENTRY: \${SENTRY_DSN:-} + REGION: \${REGION:-eu} + SHA: \${PLEXUS_COMMIT_SHA:-} + PROJECT: \${COMPOSE_PROJECT_NAME} + TOKEN: \${API_TOKEN:?the token} + ESCAPED: $\${NOT_A_VARIABLE} +`; +const PRODUCTION = + 'host: 192.0.2.1\nhostname: shop.example.com\nenv:\n MODE: production\nsecrets:\n API_TOKEN: op://acme/shop/token\n'; +const STAGING = + 'host: 192.0.2.2\nhostname: staging.shop.example.com\nenv:\n MODE: staging\nsecrets:\n API_TOKEN: op://acme/shop-staging/token\n'; + +/** What the stack's doctor unit finds that belongs to no requirement, over a stack with these files. */ +async function environmentFindings(files: Tree) { + const { of } = await webReport((web) => withStack(web, files)); + return of('stack') + .filter((f) => f.requirement === undefined) + .map((f) => f.problem); +} +const environmentFiles = (over: Tree = {}): Tree => ({ + 'compose.yaml': compose(FROM_ENV), + 'production.yaml': PRODUCTION, + 'staging.yaml': STAGING, + ...over, +}); + +test('a stack of two environments that list the same names, cover the compose file and agree on the port passes', async () => { + const { of } = await webReport((web) => withStack(web, environmentFiles())); + assert.deepEqual(of('stack'), []); +}); + +test('a stack without environment files is held to none of the environment checks', async () => { + assert.deepEqual(await environmentFindings({ 'compose.yaml': compose(FROM_ENV) }), []); +}); + +test('an environment file with an unknown key, no host, a secret that is no pointer or a name that is no word fails', async () => { + const cases: [string, string, RegExp][] = [ + ['staging', `${STAGING}port: 1\n`, /staging\.yaml: unknown key `port`/], + ['staging', STAGING.replace('host: 192.0.2.2\n', ''), /staging\.yaml: has no `host`/], + [ + 'staging', + STAGING.replace('op://acme/shop-staging/token', 'plain'), + /staging\.yaml: `secrets` `API_TOKEN` is no `op:\/\/` pointer/, + ], + ['pre-prod', STAGING, /pre-prod\.yaml: `pre-prod` is no environment name; a name is one lowercase word/], + ['Staging', STAGING, /Staging\.yaml: `Staging` is no environment name/], + ]; + for (const [name, text, problem] of cases) { + const files = environmentFiles(name === 'staging' ? { 'staging.yaml': text } : { [`${name}.yaml`]: text }); + const found = (await environmentFindings(files)).filter((p) => problem.test(p)); + assert.equal(found.length, 1, `${name}: ${text}`); + } +}); + +test('environment files that list different names under env or under secrets fail, naming the file and the name', async () => { + const env = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace(' MODE: staging\n', ' MODE: staging\n EXTRA: x\n') }), + ); + assert.deepEqual(env, ['production.yaml lists no `EXTRA` under `env`, which staging.yaml does'].sort()); + const secrets = await environmentFindings( + environmentFiles({ 'staging.yaml': `${STAGING} OTHER: op://acme/shop/other\n` }), + ); + assert.deepEqual(secrets, ['production.yaml lists no `OTHER` under `secrets`, which staging.yaml does'].sort()); +}); + +test("a variable the compose file requires that an environment lists nowhere fails; the platform's variables and defaults are exempt", async () => { + const missing = await environmentFindings( + environmentFiles({ + 'production.yaml': PRODUCTION.replace(' MODE: production\n', ''), + 'staging.yaml': STAGING.replace(' MODE: staging\n', ''), + }), + ); + assert.deepEqual(missing.sort(), [ + 'compose.yaml requires `MODE`, which production.yaml lists under neither `env` nor `secrets`', + 'compose.yaml requires `MODE`, which staging.yaml lists under neither `env` nor `secrets`', + ]); + const alone = await environmentFindings( + environmentFiles({ + 'compose.yaml': compose(FROM_ENV.replace('${MODE}', '${PLEXUS_TAG}')), + 'production.yaml': PRODUCTION.replace(' MODE: production\n', ''), + 'staging.yaml': STAGING.replace(' MODE: staging\n', ''), + }), + ); + assert.deepEqual(alone, []); +}); + +test('a variable listed under secrets covers the compose file as one under env does', async () => { + const swapped = environmentFiles({ + 'production.yaml': + 'host: 192.0.2.1\nhostname: shop.example.com\nsecrets:\n API_TOKEN: op://a/b/c\n MODE: op://a/b/mode\n', + 'staging.yaml': + 'host: 192.0.2.2\nhostname: s.example.com\nsecrets:\n API_TOKEN: op://a/b/c\n MODE: op://a/b/mode\n', + }); + assert.deepEqual(await environmentFindings(swapped), []); +}); + +test('a compose file that binds PLEXUS_LOOPBACK_PORT needs a hostname in every environment, and one that does not needs none', async () => { + const noHostname = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace('hostname: staging.shop.example.com\n', '') }), + ); + assert.deepEqual(noHostname, [ + 'staging.yaml has no `hostname`, but compose.yaml binds `PLEXUS_LOOPBACK_PORT`, which needs the public name the proxy serves', + ]); + const unbound = FROM_ENV.replace(/ {4}ports: .*\n/, ''); + const hostnames = await environmentFindings(environmentFiles({ 'compose.yaml': compose(unbound) })); + assert.deepEqual(hostnames.sort(), [ + 'production.yaml has a `hostname`, but compose.yaml binds no `PLEXUS_LOOPBACK_PORT`, so the environment gets no port and no route', + 'staging.yaml has a `hostname`, but compose.yaml binds no `PLEXUS_LOOPBACK_PORT`, so the environment gets no port and no route', + ]); +}); From 3cffcf99eb1e6135e16f077b681a04cc8e5b4e59 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:39:21 +0100 Subject: [PATCH 04/91] plx doctor holds a stack's environment files to each other and to its compose file Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.ts | 55 ++++++++++++++++++++++++++++++++ packages/lib/src/environments.ts | 43 ++++++++++++++++++++++++- packages/lib/src/index.ts | 2 ++ 3 files changed, 99 insertions(+), 1 deletion(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index a22e5fd9..6a030631 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -42,6 +42,10 @@ // one per file, whatever the marker lists; it names no requirement, and // nothing excludes a file from it. // +// Also of no requirement, and no deviation silences them: what a stack's +// environment files meet (`environmentFindings`), which a stack without +// environment files meets as it is. +// // Also of no requirement, and no deviation silences it: a repo with `stack/` // whose root marker has no `repo` key, which names it (stacks.ts, `no-repo-name`). // @@ -102,6 +106,7 @@ import { } from './compose.ts'; import { filesWithConflictMarkers } from './conflicts.ts'; import type { Context } from './context.ts'; +import { type Environment, PLATFORM_VARIABLES, requiredVariables } from './environments.ts'; import { ExecError } from './io.ts'; import { REQUIREMENT_NAME } from './lints.ts'; import { type Declaration, MARKER_FILE, parseMarker, reasonGiven } from './marker.ts'; @@ -202,6 +207,8 @@ export interface StackFacts { registries: string[]; /** The loader's problems with this stack. */ problems: StackProblem[]; + /** Its environments, as the loader reads them. */ + environments: Environment[]; /** The `package.json` of each app the stack runs, by app name; an app without one has no entry. */ packageJsons: Record; } @@ -500,6 +507,52 @@ export const CHECKS: Readonly> 'PLX-Stack/Stateful/Seed': { binds: 'stack', profile: 'stateful', check: seed }, }; +/** + * What a stack's environment files must meet, none of it a requirement yet + * and so a finding of none, which no deviation silences. A stack without + * environment files meets all of it. Each file is usable (the loader's + * `problems`, one line each); the files list the same names under `env` and + * the same names under `secrets`, one line for each name an environment + * lacks, naming the first that has it; every variable the compose file + * requires by interpolation (`requiredVariables`) is listed under `env` or + * `secrets` of each, but for the platform's (`PLATFORM_VARIABLES`); and an + * environment has a `hostname` exactly where the compose file binds + * `PLEXUS_LOOPBACK_PORT`, as the environment gets a port and a route only then. + */ +function environmentFindings(stack: StackFacts): string[] { + const { environments, compose } = stack; + const problems = environments.flatMap((e) => e.problems); + for (const key of ['env', 'secrets'] as const) { + const names = [...new Set(environments.flatMap((e) => Object.keys(e[key])))]; + for (const name of names) { + const holder = environments.find((e) => name in e[key]); + for (const e of environments) + if (holder && !(name in e[key])) + problems.push(`${e.name}.yaml lists no \`${name}\` under \`${key}\`, which ${holder.name}.yaml does`); + } + } + if (compose && environments.length > 0) { + for (const variable of requiredVariables(compose).filter((v) => !PLATFORM_VARIABLES.includes(v))) + for (const e of environments) + if (!(variable in e.env) && !(variable in e.secrets)) + problems.push( + `compose.yaml requires \`${variable}\`, which ${e.name}.yaml lists under neither \`env\` nor \`secrets\``, + ); + const binds = Object.values(compose.services).some((service) => portsOf(service).some(bindsLoopbackVar)); + for (const e of environments) { + if (binds && e.hostname === undefined) + problems.push( + `${e.name}.yaml has no \`hostname\`, but compose.yaml binds \`PLEXUS_LOOPBACK_PORT\`, which needs the public name the proxy serves`, + ); + if (!binds && e.hostname !== undefined) + problems.push( + `${e.name}.yaml has a \`hostname\`, but compose.yaml binds no \`PLEXUS_LOOPBACK_PORT\`, so the environment gets no port and no route`, + ); + } + } + return problems; +} + /** * What the markers as configuration must meet (sites.ts): the root's `version` * is the `plx` pin's, no other marker has one, and no key is answered in two @@ -680,6 +733,7 @@ function diagnoseUnit(unit: Facts, known: Set): UnitReport { if (deviations.includes(name)) continue; for (const problem of run(c, unit, profile)) findings.push({ requirement: name, problem }); } + if (unit.kind === 'stack') for (const problem of environmentFindings(unit)) findings.push({ problem }); if (isRepo(unit)) { for (const problem of repoNaming(unit)) findings.push({ problem }); for (const file of unit.conflicted ?? []) findings.push({ problem: `\`${file}\` holds a conflict marker` }); @@ -891,6 +945,7 @@ async function readStack(ctx: Context, repo: RepoFacts, stack: Stack, base: stri repoApps: loaded?.apps ?? [], registries: loaded?.prefixes ?? [], problems: (loaded?.problems ?? []).filter((p) => p.stack === stack.name), + environments: stack.environments, packageJsons, }; } diff --git a/packages/lib/src/environments.ts b/packages/lib/src/environments.ts index 1a7d8f1a..9b7997dd 100644 --- a/packages/lib/src/environments.ts +++ b/packages/lib/src/environments.ts @@ -19,11 +19,28 @@ // names, and never throws: whatever makes a file unusable is a line of its // `problems` that names the file, and the values it could read are returned // all the same, so that every problem is found in one run. +// +// `requiredVariables` lists the variables a compose file needs its +// environment to give: those it interpolates without a default (`${NAME}`, +// `$NAME`, `${NAME:?message}`, `${NAME?message}`), not the ones with a +// default or an alternative (`${NAME:-x}`, `${NAME-x}`, `${NAME:+x}`, +// `${NAME+x}`); `$$` is compose's escape and no variable. It reads every string +// of the services, keys included. The variables the platform supplies itself +// (`PLATFORM_VARIABLES`) are among them where the file uses them, and are +// listed in no environment file. import { join } from 'node:path'; import { parse } from 'yaml'; -import { isMapping } from './compose.ts'; +import { type Compose, isMapping } from './compose.ts'; import type { Context } from './context.ts'; +/** The variables the platform and the deployer supply to a stack, which no environment file lists: the project name and the loopback port in `.env`, the tag and the commit at deploy time. */ +export const PLATFORM_VARIABLES: readonly string[] = [ + 'COMPOSE_PROJECT_NAME', + 'PLEXUS_LOOPBACK_PORT', + 'PLEXUS_TAG', + 'PLEXUS_COMMIT_SHA', +]; + /** One stack on one host, as its file states it. */ export interface Environment { /** The file's name without `.yaml`. */ @@ -107,3 +124,27 @@ async function readEnvironment(ctx: Context, dir: string, name: string): Promise } return environment; } + +/** A variable of a string: `$NAME`, or `${NAME` with what follows it up to the brace. */ +const REFERENCE = /(\$+)(?:([A-Za-z_][A-Za-z0-9_]*)|\{([A-Za-z_][A-Za-z0-9_]*)([^}]*)\})/g; + +/** The variables a compose file interpolates without a default, in the order found, once each. */ +export function requiredVariables(compose: Compose): string[] { + const found = new Set(); + const visit = (value: unknown): void => { + if (typeof value === 'string') { + for (const [, dollars, bare, braced, rest] of value.matchAll(REFERENCE)) { + if ((dollars?.length ?? 0) % 2 === 0) continue; + if (bare !== undefined) found.add(bare); + else if (braced !== undefined && !/^:?[-+]/.test(rest ?? '')) found.add(braced); + } + } else if (Array.isArray(value)) value.forEach(visit); + else if (isMapping(value)) + for (const [key, child] of Object.entries(value)) { + visit(key); + visit(child); + } + }; + visit(compose.services); + return [...found]; +} diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 345c709d..ffb3ff36 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -79,7 +79,9 @@ export { body, describe, type Plan, run, type Step, write } from './effects.ts'; export { envFlag } from './envFlag.ts'; export { type Environment, + PLATFORM_VARIABLES, readEnvironments, + requiredVariables, } from './environments.ts'; export { frontmatterField, setFrontmatterField } from './frontmatter.ts'; export { From 95b35b77475292e06c8b04b12a630c54e8a9c031 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:40:06 +0100 Subject: [PATCH 05/91] Test: a secret that is no pointer is listed under its name Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/stacks.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/lib/src/stacks.test.ts b/packages/lib/src/stacks.test.ts index bf6e839c..aee80315 100644 --- a/packages/lib/src/stacks.test.ts +++ b/packages/lib/src/stacks.test.ts @@ -490,3 +490,9 @@ test('an empty environment file lacks its host and nothing else', async () => { assert.equal(environment?.host, undefined); assert.equal(environment?.problems.length, 1); }); + +test('a secret that is no pointer is still listed under its name, so that only its own problem is reported', async () => { + const [environment] = await environmentsOf({ 'staging.yaml': 'host: 192.0.2.1\nsecrets:\n TOKEN: plain\n' }); + assert.deepEqual(environment?.secrets, { TOKEN: 'plain' }); + assert.equal(environment?.problems.length, 1); +}); From 80a328a026cb485852370fb74cfb8ca77c4f84d8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:40:19 +0100 Subject: [PATCH 06/91] A secret that is no pointer is listed under its name and reported once Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/environments.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/lib/src/environments.ts b/packages/lib/src/environments.ts index 9b7997dd..7e53fb80 100644 --- a/packages/lib/src/environments.ts +++ b/packages/lib/src/environments.ts @@ -14,7 +14,8 @@ // and without it the environment gets no loopback port and no route // env a map of names to plain values (string, number or boolean, read // as the string compose would see); absent reads as empty -// secrets a map of names to `op://` pointers, strings; absent reads as empty +// secrets a map of names to `op://` pointers, strings; absent reads as empty; +// a string that is no pointer is returned and is a problem // `readEnvironments` returns one `Environment` per file in the order of their // names, and never throws: whatever makes a file unusable is a line of its // `problems` that names the file, and the values it could read are returned @@ -118,8 +119,11 @@ async function readEnvironment(ctx: Context, dir: string, name: string): Promise if (key === 'env') { if (['string', 'number', 'boolean'].includes(typeof value)) into[variable] = String(value); else problem(`\`env\` \`${variable}\` is not a plain value (a string, a number or a boolean)`); - } else if (typeof value === 'string' && value.startsWith('op://')) into[variable] = value; - else problem(`\`secrets\` \`${variable}\` is no \`op://\` pointer`); + } else { + if (typeof value === 'string') into[variable] = value; + if (typeof value !== 'string' || !value.startsWith('op://')) + problem(`\`secrets\` \`${variable}\` is no \`op://\` pointer`); + } } } return environment; From b58a11d65f07b9327672185afaa447f23a6c4190 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:45:38 +0100 Subject: [PATCH 07/91] test: the platform playbook leaves a host's deployments of an earlier version as they were A run on a host that carries a deployment and the routes the earlier version rendered, with plexus_apps still set: it says the variable is no longer read, changes none of the deployment's files nor apps.caddy, runs no docker command, and the route still answers. Red: the roles still read the records. Co-Authored-By: Claude Opus 5.5 --- mise.toml | 6 +- tests/platform-playbook.sh | 184 +++++++++++++++++++++++++++++++++++++ 2 files changed, 187 insertions(+), 3 deletions(-) create mode 100755 tests/platform-playbook.sh diff --git a/mise.toml b/mise.toml index c9812737..bb643cc6 100644 --- a/mise.toml +++ b/mise.toml @@ -75,7 +75,7 @@ run = 'mise run check-js ${usage_name:+"$usage_name"}' [tasks.test] depends = ["install"] -description = "Run check, then the tests of the Terraform modules (against a mocked provider, and offline), the order of the tasks of plexus.ci.playbook, the stack playbook against this machine's Docker daemon (skipped without one) and the unit tests of the packages (the other roles are exercised by the dogfood tenant's playbook runs, the mounts by its pipelines)" +description = "Run check, then the tests of the Terraform modules (against a mocked provider, and offline), the order of the tasks of plexus.ci.playbook, the stack playbook against this machine's Docker daemon and the platform playbook against containers of it (each skipped without one), and the unit tests of the packages (the other roles are exercised by the dogfood tenant's playbook runs, the mounts by its pipelines)" usage = 'arg "[name]" help="Package to test, by its directory name under packages/ (e.g. lib, defaults to all)"' run = ''' dir= @@ -166,9 +166,9 @@ hide = true run = 'tests/terraform-modules.sh check' [tasks.test-ansible] -description = "What the playbooks must do that their syntax check does not hold: the order of the tasks of plexus.ci.playbook (the vault's CLI after the jobs' user, before the first vault read), and plexus.platform.stack deploying a stack on this machine's Docker daemon (skipped without one)" +description = "What the playbooks must do that their syntax check does not hold: the order of the tasks of plexus.ci.playbook (the vault's CLI after the jobs' user, before the first vault read), plexus.platform.stack deploying a stack on this machine's Docker daemon, and plexus.platform.playbook preparing a host that is a container of it (each skipped without one)" hide = true -run = ['./tests/link-collections.sh', './tests/runner-host-vault-cli.sh', './tests/stack-playbook.sh'] +run = ['./tests/link-collections.sh', './tests/runner-host-vault-cli.sh', './tests/stack-playbook.sh', './tests/platform-playbook.sh'] # The collections path check-ops fills and reads; link-collections fills it here too, so that the task works alone in a fresh checkout. env = { ANSIBLE_HOME = "{{config_root}}/.ansible", ANSIBLE_COLLECTIONS_PATH = "{{config_root}}/.ansible/collections" } diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh new file mode 100755 index 00000000..53182852 --- /dev/null +++ b/tests/platform-playbook.sh @@ -0,0 +1,184 @@ +#!/usr/bin/env bash +# The platform playbook (plexus.platform.playbook) against hosts that are +# containers of this machine's Docker daemon: Debian with systemd, sudo, and +# Caddy's binary and unit as its package installs them, reached by Ansible's +# docker connection. It runs the platform layer's roles (--tags platform) but +# caddy, whose apt repository would need the network on every run, and reads +# users, directories, sudo rules, the proxy's routes as curl on the host gets +# them, and the files of a deployment. A host's `docker` is a stand-in that +# records its arguments, so that a run that starts or re-creates nothing can be +# seen to: the hosts have no Docker daemon of their own. +# +# Run by `mise test` (its task test-ansible), beside the stack playbook's +# test. It needs a Docker daemon that lets a container run systemd (the +# capability SYS_ADMIN, AppArmor unconfined, a cgroup namespace of its own), +# and the network once for debian:13, caddy:2 and Debian's packages; where +# either is missing, it says so and passes. Every container and image it +# creates is named plxplatform-…, publishes no port, and is removed when +# it ends, whether a case failed or not. +set -euo pipefail +cd "$(dirname "$0")/.." + +if ! docker info >/dev/null 2>&1; then + echo "platform-playbook: no Docker daemon reachable; skipped" + exit 0 +fi + +run=plxplatform-$$ +work=$(mktemp -d) + +cleanup() { + docker ps -a --format '{{.Names}}' | grep "^$run" | xargs -r docker rm -f -v >/dev/null || true + docker image rm "$run:host" >/dev/null 2>&1 || true + rm -rf "$work" +} +trap cleanup EXIT +trap 'exit 130' INT TERM HUP + +fail() { + echo "✗ $case: $*" >&2 + [ ! -f "$work/out" ] || sed 's/^/ /' "$work/out" >&2 + exit 1 +} + +# The host's image: what a Debian host has when the platform layer's roles run +# on it, the proxy included, and the stand-in for docker. +mkdir "$work/image" +cat >"$work/image/Dockerfile" <<'EOF' +FROM caddy:2 AS caddy +FROM debian:13 +RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \ + systemd systemd-sysv python3 sudo curl >/dev/null && rm -rf /var/lib/apt/lists/* +COPY --from=caddy /usr/bin/caddy /usr/bin/caddy +COPY caddy.service /etc/systemd/system/caddy.service +COPY docker /usr/local/bin/docker +RUN useradd --system --home-dir /var/lib/caddy --create-home --shell /usr/sbin/nologin caddy \ + && mkdir /etc/caddy && printf ':80 {\n\trespond "the package default"\n}\n' >/etc/caddy/Caddyfile \ + && systemctl enable caddy +CMD ["sh", "-c", "mount -o remount,rw /sys/fs/cgroup && exec /sbin/init"] +EOF +# The unit of Caddy's Debian package, without its sandboxing. +cat >"$work/image/caddy.service" <<'EOF' +[Unit] +Description=Caddy +After=network.target +[Service] +Type=notify +User=caddy +Group=caddy +ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile +ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile --force +TimeoutStopSec=5s +[Install] +WantedBy=multi-user.target +EOF +cat >"$work/image/docker" <<'EOF' +#!/bin/sh +echo "$*" >>/var/log/docker-calls +EOF +chmod +x "$work/image/docker" +if ! docker build -q -t "$run:host" "$work/image" >"$work/build" 2>&1; then + echo "platform-playbook: the host's image could not be built (debian:13, caddy:2 or Debian's packages not to be had); skipped" + sed 's/^/ /' "$work/build" + exit 0 +fi + +# host : a host started from the image, booted, with its inventory at +# $work/.yml; the name is the container's, $run-. +host() { + docker run -d --name "$run-$1" --hostname "$1" --cgroupns=private --cap-add SYS_ADMIN \ + --security-opt apparmor=unconfined --tmpfs /run --tmpfs /run/lock -e container=docker "$run:host" >/dev/null + if ! timeout 60 docker exec "$run-$1" systemctl is-system-running --wait >/dev/null 2>&1 && + ! docker exec "$run-$1" systemctl is-active -q caddy 2>/dev/null; then + echo "platform-playbook: systemd does not boot in a container on this Docker daemon; skipped" + exit 0 + fi + cat >"$work/$1.yml" < [arguments]: one run of the platform layer on the host; its exit +# code in $status, its output in $work/out. +play() { + status=0 + timeout 600 ansible-playbook -i "$work/$1.yml" --tags platform --skip-tags caddy "${@:2}" \ + plexus.platform.playbook "$work/out" 2>&1 || status=$? +} + +# on : a command on the host as root; as : as that user. +on() { docker exec "$run-$1" "${@:2}"; } +as() { docker exec -u "$1" "$run-$2" "${@:3}"; } +# get : the status and body of a request the proxy serves on the host. +get() { on "$1" curl -s -m 5 -w ' %{http_code}' -H "Host: $2" "http://127.0.0.1$3" || true; } +# backend : a service on 127.0.0.1: of the host that answers every path with . +backend() { + on "$1" sh -c "mkdir -p /srv/$2 && printf %s '$3' >/srv/$2/index.html && cp /srv/$2/index.html /srv/$2/healthz" + on "$1" systemd-run -q --unit "backend-$2" python3 -m http.server -b 127.0.0.1 -d "/srv/$2" "$2" + for _ in $(seq 50); do on "$1" curl -s -o /dev/null "http://127.0.0.1:$2/" && return; sleep 0.1; done +} +# snapshot : every file below the paths with owner, mode, size, time and content. +snapshot() { + on "$1" sh -c 'find "$@" -exec stat -c "%n %U:%G %a %s %Y" {} + | sort; find "$@" -type f -exec sha256sum {} + | sort' - "${@:2}" +} + +case='a host that carries deployments of an earlier version' +host migrated +# As the earlier platform playbook left it: the deployment's directory with its +# files, the routes rendered from the records into apps.caddy, the root +# configuration importing them, and the deployment answering on its port. +on migrated useradd --create-home --shell /bin/bash plexus +on migrated sh -c 'mkdir -p /opt/stacks/shop-production && cd /opt/stacks/shop-production && + printf "COMPOSE_PROJECT_NAME=shop-production\nPLEXUS_LOOPBACK_PORT=3001\nSHOP_URL=https://shop.example.com\n" >.env && + printf "DB_PASSWORD=secret\n" >.env.secret && + printf "services:\n web:\n image: ghcr.io/acme/shop@sha256:%064d\n" 2 >compose.yaml && + printf "services:\n web:\n image: ghcr.io/acme/shop@sha256:%064d\n" 1 >compose.yaml.prev && + chown -R plexus:plexus . && chmod 0750 . && chmod 0640 .env compose.yaml compose.yaml.prev && chmod 0600 .env.secret' +cat >"$work/apps.caddy" <<'EOF' +# Managed by Ansible (plexus.platform.ingress) — one route per app record on this host. +http://shop.example.com { + encode zstd gzip + # shop (production) + + handle { + respond /healthz 403 + reverse_proxy 127.0.0.1:3001 + } +} +EOF +docker cp -q "$work/apps.caddy" "$run-migrated:/etc/caddy/apps.caddy" +on migrated sh -c 'printf "# Managed by Ansible (plexus.platform.ingress).\nimport apps.caddy\n" >/etc/caddy/Caddyfile && systemctl restart caddy' +backend migrated 3001 'shop production' +[ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the fixture's route does not answer" +# The group's variables as the operations template renders them, and the +# records the earlier version read, with a value that differs from the .env in +# place and a secret: a run that still read them would rewrite both. +cat >>"$work/migrated.yml" <<'EOF' + plexus_deploy_root: /opt/stacks + plexus_up: true + plexus_ghcr_user: "" + plexus_ghcr_token: "" + plexus_apps: + - name: shop + environment: production + host: shop.example.com + loopback_port: 3001 + env: { SHOP_URL: https://www.example.com } + secrets: { DB_PASSWORD: op://acme/shop/db } +EOF +before=$(snapshot migrated /opt/stacks/shop-production /etc/caddy/apps.caddy) +play migrated +[ "$status" = 0 ] || fail "exit code $status" +grep -q 'plexus_apps is no longer read' "$work/out" || fail "no message that plexus_apps is no longer read" +[ "$(snapshot migrated /opt/stacks/shop-production /etc/caddy/apps.caddy)" = "$before" ] || fail "a deployment's file or apps.caddy changed" +[ -z "$(on migrated cat /var/log/docker-calls 2>/dev/null)" ] || fail "docker was run: $(on migrated cat /var/log/docker-calls)" +[ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the deployment's route no longer answers" +on migrated systemctl reload caddy || fail "the proxy does not reload" +[ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the deployment's route no longer answers after a reload" +echo "✓ $case" From e596fbd47985c6979e4b991e9dfea202110c517d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:47:24 +0100 Subject: [PATCH 08/91] The platform playbook no longer reads plexus_apps The roles apps and secrets go, and with them every per-deployment task: no directory, .env, .env.secret or docker compose up from the records. ingress renders no routes any more; the root Caddyfile imports the apps.caddy earlier versions rendered for as long as it is there, by its absolute path, so the root is validated as a whole before it replaces the one in place. A host that still sets plexus_apps is told the variable is no longer read. The registry login of the deploy user moves to deploy_user. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/galaxy.yml | 6 +- ansible/platform/playbooks/playbook.yml | 48 +++---- ansible/platform/roles/apps/handlers/main.yml | 19 --- ansible/platform/roles/apps/tasks/app.yml | 134 ------------------ ansible/platform/roles/apps/tasks/main.yml | 31 ---- .../roles/deploy_user/defaults/main.yml | 14 +- .../platform/roles/deploy_user/tasks/main.yml | 14 +- ansible/platform/roles/ingress/tasks/main.yml | 72 +++------- .../roles/ingress/templates/Caddyfile.j2 | 61 -------- .../roles/ingress/templates/root.Caddyfile.j2 | 10 +- .../platform/roles/secrets/handlers/main.yml | 22 --- ansible/platform/roles/secrets/tasks/app.yml | 46 ------ ansible/platform/roles/secrets/tasks/main.yml | 30 ---- tests/all-roles.yml | 2 - 14 files changed, 71 insertions(+), 438 deletions(-) delete mode 100644 ansible/platform/roles/apps/handlers/main.yml delete mode 100644 ansible/platform/roles/apps/tasks/app.yml delete mode 100644 ansible/platform/roles/apps/tasks/main.yml delete mode 100644 ansible/platform/roles/ingress/templates/Caddyfile.j2 delete mode 100644 ansible/platform/roles/secrets/handlers/main.yml delete mode 100644 ansible/platform/roles/secrets/tasks/app.yml delete mode 100644 ansible/platform/roles/secrets/tasks/main.yml diff --git a/ansible/platform/galaxy.yml b/ansible/platform/galaxy.yml index 5874253e..eebe1811 100644 --- a/ansible/platform/galaxy.yml +++ b/ansible/platform/galaxy.yml @@ -7,9 +7,9 @@ readme: README.md authors: - David Julian Albers description: >- - The platform layer (PLX-Platform): what makes an existing host run a tenant's apps — - deploy_user, caddy, ingress, secrets, apps — and the playbook plexus.platform.playbook that - mounts them with the host baseline on the inventory group platform; and the playbook + The platform layer (PLX-Platform): what prepares an existing host for a tenant's stacks — + deploy_user, caddy, ingress — and the playbook plexus.platform.playbook that mounts them + with the host baseline on the inventory group platform; and the playbook plexus.platform.stack, which deploys one environment of a stack onto one host. license: - GPL-3.0-or-later diff --git a/ansible/platform/playbooks/playbook.yml b/ansible/platform/playbooks/playbook.yml index b5406d4d..553846a5 100644 --- a/ansible/platform/playbooks/playbook.yml +++ b/ansible/platform/playbooks/playbook.yml @@ -1,16 +1,22 @@ --- # The platform layer on a tenant's app hosts (PLX-Platform): the host -# baseline, then what makes the host run the tenant's apps, then the lock-down -# roles that have to come last. Mounted on the inventory group `platform`. +# baseline, then what prepares the host for stacks, then the lock-down roles +# that have to come last. Mounted on the inventory group `platform`. # # ansible-playbook plexus.platform.playbook # everything -# ansible-playbook plexus.platform.playbook --tags apps,secrets # the everyday pass +# ansible-playbook plexus.platform.playbook --tags platform # the layer without the baseline # ansible-playbook plexus.platform.playbook --limit host-a --tags ingress # # Tags: every play carries its layer (`host`, `platform`) and every role its -# own name, so `--tags platform` is the whole layer and `--tags apps` one role. -# Not a deploy: deploying is the verb's act (§ 6 PLX-Delivery); this playbook -# binds apps to the host and hands them their environment. +# own name, so `--tags platform` is the whole layer and `--tags ingress` one role. +# It knows no stack: it prepares what every stack's environment needs on the +# host (the deploy user, the deploy root, the proxy with its directory of route +# fragments, and the one rule by which the deploy user reloads the proxy), and +# the stack playbook (plexus.platform.stack) does everything one environment +# needs. It starts, re-creates and removes no container, and changes nothing +# below the deploy root but the root's own owner. `plexus_apps`, the records of +# earlier versions, is not read; a host that still sets it is told so, and the +# run goes on. # # A fresh host is reached as root once (`-u root`), which creates the admins; # every later run connects as an admin, and the first of those closes root @@ -46,12 +52,19 @@ - name: Gather facts ansible.builtin.setup: tags: [always] + - name: Say that plexus_apps is no longer read + when: plexus_apps | default([]) | length > 0 + ansible.builtin.debug: + msg: >- + plexus_apps is no longer read: the platform playbook lays out no environment and writes no .env, + .env.secret or route from it; the stack playbook does, from the stack's environment file. What earlier + versions wrote from it stays as it was, the routes in /etc/caddy/apps.caddy among it. Remove the records + once every environment on this host deploys from its environment file. + tags: [always] roles: - { role: plexus.platform.deploy_user, tags: [deploy_user] } - { role: plexus.platform.caddy, tags: [caddy] } - { role: plexus.platform.ingress, tags: [ingress] } - - { role: plexus.platform.secrets, tags: [secrets] } # before apps, so the first up sees the secrets - - { role: plexus.platform.apps, tags: [apps] } - name: Lock down the platform hosts hosts: platform @@ -65,22 +78,3 @@ roles: - { role: plexus.host.firewall, tags: [firewall] } # after the roles that open ports in it - { role: plexus.host.sshd, tags: [sshd] } # last: closes root logins once an admin has logged in - -# The apps role records an app whose start failed and carries on with the -# others; the failure is raised here, once per host and after the lock-down -# roles, so that a failed start never leaves a host without its firewall and -# sshd settings. Any other failure (a rotation handler, the registry login, -# writing .env, resolving the secrets) still fails the host before them. Tagged `platform` and `apps`, so `--tags apps` reports it too. -- name: Report the apps that failed to start - hosts: platform - gather_facts: false - tags: [platform, apps] - tasks: - - name: Fail the host for the apps that did not start - when: apps_failures | default([]) | length > 0 - ansible.builtin.fail: - msg: |- - {{ apps_failures | length }} app(s) did not start: - {% for f in apps_failures %} - - {{ f.app }}: '{{ f.task }}' failed (rc {{ f.rc }}): {{ f.output }} - {% endfor %} diff --git a/ansible/platform/roles/apps/handlers/main.yml b/ansible/platform/roles/apps/handlers/main.yml deleted file mode 100644 index 16aaba86..00000000 --- a/ansible/platform/roles/apps/handlers/main.yml +++ /dev/null @@ -1,19 +0,0 @@ ---- -# Rotation closes inside the playbook (PLX-Secrets): environment is injected at -# container creation, so a rewritten .env or .env.secret rotates a file, not a -# credential, until the affected containers are re-created. A bare `up -d` — -# the same invocation the deploy verb and a human use, since compose reads -# .env implicitly and the image is pinned in the file — re-creates exactly the -# services whose environment differs. Skipped where the deploy verb has not -# placed a compose file yet. -- name: Re-create app containers - ansible.builtin.command: - cmd: docker compose up -d - chdir: "{{ item }}" - loop: "{{ apps_dirs | default([]) }}" - become: true - become_user: "{{ plexus_deploy_user }}" - when: plexus_up | bool - register: apps_recreate - changed_when: "'Recreated' in apps_recreate.stderr or 'Started' in apps_recreate.stderr" - failed_when: apps_recreate.rc != 0 and 'no configuration file' not in apps_recreate.stderr diff --git a/ansible/platform/roles/apps/tasks/app.yml b/ansible/platform/roles/apps/tasks/app.yml deleted file mode 100644 index e09eb83c..00000000 --- a/ansible/platform/roles/apps/tasks/app.yml +++ /dev/null @@ -1,134 +0,0 @@ ---- -# The deployment's slug (§ 3 PLX-Platform): -, in every -# environment; the stack playbook works in the same directory under the same -# project name. -- name: "{{ app.name }} | resolve the deployment slug" - ansible.builtin.set_fact: - apps_slug: "{{ app.name ~ '-' ~ app.environment }}" - -- name: "{{ app.name }} | resolve app dir" - ansible.builtin.set_fact: - apps_dir: "{{ plexus_deploy_root }}/{{ apps_slug }}" - -- name: "{{ app.name }} | create app dir" - ansible.builtin.file: - path: "{{ apps_dir }}" - state: directory - owner: "{{ plexus_deploy_user }}" - group: "{{ plexus_deploy_user }}" - mode: "0750" - -# The app's run shape — compose.yaml — is NOT placed here. It lives in the -# app's source repo (an app repo, or the operations repo's own apps// for -# third-party software) and the deploy verb renders it at deploy time with the -# image pinned, so the compose file on the host always names the image it -# serves (§ 2 PLX-App). Three files in the app dir, one writer each (§ 3 PLX-Platform): -# this role owns .env, secrets owns .env.secret (PLX-Secrets), and -# the deploy verb owns compose.yaml. -# Compose reads .env from the project dir implicitly, so every invocation — -# the verb's, the rotation handler's, a human's — is a bare `docker compose`. - -# .env (§ 3 PLX-App, § 3 PLX-Platform), three sections: compose's own setting, the reserved -# PLEXUS_ bindings, then the non-secret values the inventory provides for the -# app (`app.env`). The project name is pinned to the deployment's slug, so that -# container, network and volume names never depend on where compose was -# invoked from. The loopback port is the one assigned -# in the inventory, interpolated by compose as ${PLEXUS_LOOPBACK_PORT:?…}, so a -# directory without this file refuses to start instead of publishing on a -# random port (PLX-Stack/LoopbackPort). This -# playbook is the file's only writer and always overwrites — the inventory is -# the truth. -- name: "{{ app.name }} | write .env (compose setting, platform bindings, values)" - ansible.builtin.copy: - dest: "{{ apps_dir }}/.env" - content: | - # Written by the platform playbook from the tenant inventory. Do not edit. - # Compose settings. - COMPOSE_PROJECT_NAME={{ apps_slug }} - - # Platform bindings (reserved PLEXUS_ prefix, § 4 PLX-App). - PLEXUS_LOOPBACK_PORT={{ app.loopback_port }} - - # Values from the inventory record, apps[].env (§ 3 PLX-Platform). - {% for key, value in (app.env | default({})).items() %} - {{ key }}={{ value }} - {% endfor %} - owner: "{{ plexus_deploy_user }}" - group: "{{ plexus_deploy_user }}" - mode: "0640" - notify: Re-create app containers - -- name: "{{ app.name }} | log in to GHCR as the deploy user" - ansible.builtin.command: - cmd: "docker login ghcr.io -u {{ plexus_ghcr_user }} --password-stdin" - stdin: "{{ plexus_ghcr_token }}" - become: true - become_user: "{{ plexus_deploy_user }}" - when: plexus_ghcr_token | length > 0 - no_log: true - changed_when: false - -# Nothing to bring up until the deploy verb has placed the run shape: a fresh -# host stays provisioned-but-empty until the first CI deploy (or a hand-run of -# the verb), which is the operator's supervised act (§ 6 PLX-Delivery). The -# verb pulls the image before it places compose.yaml, so a compose.yaml on the -# host means its image existed: an absent file is the one "new app" case, and -# a start that fails once the file is there is a failure, not a pending first -# deploy. (A registry such as GHCR answers `denied` for a missing image -# as for bad credentials, so the failure cannot be read for "not there yet".) -- name: "{{ app.name }} | check whether the deploy verb has placed compose.yaml" - ansible.builtin.stat: - path: "{{ apps_dir }}/compose.yaml" - register: apps_compose - -- name: "{{ app.name }} | nothing deployed yet (no compose.yaml), so nothing to start" - when: plexus_up | bool and not apps_compose.stat.exists - ansible.builtin.debug: - msg: >- - {{ app.name }}: no compose.yaml in {{ apps_dir }}, so nothing has been deployed yet and there is no image to start. - Run the CI deploy (or the deploy verb by hand) to bring it up. - -# Runs as the deploy user so a private registry works: that's where the GHCR -# login above put the credentials, and it's the same user the CI deploy verb -# uses. There is no separate pull: `up -d` pulls only the images the host does -# not hold (compose's default pull policy, `missing`), so an app whose image is -# on the host starts without the registry (a service that sets its own -# pull_policy, `always` for instance, still contacts it), and a playbook run no longer -# refreshes a floating tag, which fits a playbook that is not a deploy. -# -# A failure of the start does not stop the other apps: it is recorded (app, -# task, rc, output) in `apps_failures`, and the last play of the platform -# playbook fails the host once, listing every failed app, after the handlers -# and the lock-down roles have run. Only that play raises the failure: a -# playbook that uses this role without it must raise `apps_failures` itself. A failed app's dir is kept from the -# rotation handlers (this role's and the secrets role's), which would only run -# the failing `up -d` again; the next run's `up -d` re-creates it with the -# rotated environment. -- name: "{{ app.name }} | start" - when: plexus_up | bool and apps_compose.stat.exists - become: true - become_user: "{{ plexus_deploy_user }}" - block: - - name: "{{ app.name }} | docker compose up -d" - ansible.builtin.command: - cmd: docker compose up -d - chdir: "{{ apps_dir }}" - register: apps_up - changed_when: "'Started' in apps_up.stderr or 'Recreated' in apps_up.stderr or 'Created' in apps_up.stderr" - rescue: - - name: "{{ app.name }} | record the failed start" - ansible.builtin.set_fact: - apps_failures: >- - {{ (apps_failures | default([])) + [{ - 'app': apps_slug, - 'dir': apps_dir, - 'task': ansible_failed_task.name, - 'rc': ansible_failed_result.rc | default('none'), - 'output': ([ansible_failed_result.stderr | default(''), ansible_failed_result.stdout | default(''), - ansible_failed_result.msg | default('')] | map('trim') | select | first | default('no output')) - }] }} - -- name: "{{ app.name }} | remember the app dir for the rotation handler" - when: apps_slug not in (apps_failures | default([]) | map(attribute='app') | list) - ansible.builtin.set_fact: - apps_dirs: "{{ (apps_dirs | default([])) + [apps_dir] }}" diff --git a/ansible/platform/roles/apps/tasks/main.yml b/ansible/platform/roles/apps/tasks/main.yml deleted file mode 100644 index 3fd949f2..00000000 --- a/ansible/platform/roles/apps/tasks/main.yml +++ /dev/null @@ -1,31 +0,0 @@ ---- -# The app name is the join key across repos (§ 3 PLX-Platform): the inventory -# record, the host dir and the compose project all key on it, so it is unique -# per tenant and environment — across every app repo and this platform repo. -# Every record names its environment; the deployment's slug on the host is -# -, for every environment. The slug names the host dir and -# is the compose project's name (app.yml writes it to .env). A directory of an -# earlier layout is left as it was: no task here moves or removes one. -- name: Assert every app record names its environment - ansible.builtin.assert: - that: - - plexus_apps | rejectattr('environment', 'defined') | list | length == 0 - fail_msg: >- - {% set missing = plexus_apps | rejectattr('environment', 'defined') | map(attribute='name', default='?') | list -%} - plexus_apps: the record{{ 's' if missing | length > 1 else '' }} '{{ missing | join("', '") }}' - name{{ '' if missing | length > 1 else 's' }} no environment; every record names one, for example environment: production - -- name: Assert app names are unique per tenant and environment - ansible.builtin.assert: - that: - - >- - plexus_apps | map(attribute='name') | zip(plexus_apps | map(attribute='environment')) - | map('join', '@') | list | unique | length == plexus_apps | length - fail_msg: "Duplicate app in plexus_apps — one record per app and environment (§ 3 PLX-Platform)." - -- name: Configure and start each app - ansible.builtin.include_tasks: app.yml - loop: "{{ plexus_apps }}" - loop_control: - loop_var: app - label: "{{ app.name }}" diff --git a/ansible/platform/roles/deploy_user/defaults/main.yml b/ansible/platform/roles/deploy_user/defaults/main.yml index 8cb44cdd..58ff1698 100644 --- a/ansible/platform/roles/deploy_user/defaults/main.yml +++ b/ansible/platform/roles/deploy_user/defaults/main.yml @@ -1,7 +1,15 @@ --- -# The unprivileged user that owns the app directories and runs the deploy -# verb over SSH (plexus_deploy_user, plexus_deploy_pubkey: shared with -# apps, so they keep the plexus_ prefix). +# The unprivileged user that owns the deploy root and as which the stack +# playbook deploys over SSH. The plexus_ variables are shared with other roles +# (plexus.host.docker adds the user to the docker group), so they keep that +# prefix and have no default here; set them in the operations repo's group +# variables: +# plexus_deploy_user the user's name +# plexus_deploy_pubkey the public key the deployer connects with; unset or +# empty: no key is authorized +# plexus_ghcr_user the registry login the user pulls the stacks' images +# plexus_ghcr_token with, renewed on every run; an unset or empty token: +# no login, the images are public or an earlier login stands # Further groups for the deploy user, e.g. the group an image's sshd policy # admits logins from. diff --git a/ansible/platform/roles/deploy_user/tasks/main.yml b/ansible/platform/roles/deploy_user/tasks/main.yml index 136b30eb..6bd1fa9b 100644 --- a/ansible/platform/roles/deploy_user/tasks/main.yml +++ b/ansible/platform/roles/deploy_user/tasks/main.yml @@ -7,7 +7,7 @@ groups: "{{ deploy_user_groups }}" append: true -- name: Authorize the deploy key (CI runs the deploy verb as this user) +- name: Authorize the deploy key (the stack playbook connects as this user) ansible.posix.authorized_key: user: "{{ plexus_deploy_user }}" key: "{{ plexus_deploy_pubkey }}" @@ -18,3 +18,15 @@ ansible.builtin.debug: msg: Skipping deploy key authorization as plexus_deploy_pubkey is undefined or empty. when: plexus_deploy_pubkey | default('') | length == 0 + +# The stack playbook pulls on the host, as this user, so the credentials sit in +# the user's own Docker configuration. +- name: Log in to GHCR as the deploy user + ansible.builtin.command: + cmd: "docker login ghcr.io -u {{ plexus_ghcr_user }} --password-stdin" + stdin: "{{ plexus_ghcr_token }}" + become: true + become_user: "{{ plexus_deploy_user }}" + when: plexus_ghcr_token | default('') | length > 0 + no_log: true + changed_when: false diff --git a/ansible/platform/roles/ingress/tasks/main.yml b/ansible/platform/roles/ingress/tasks/main.yml index c3dade3c..0bff6299 100644 --- a/ansible/platform/roles/ingress/tasks/main.yml +++ b/ansible/platform/roles/ingress/tasks/main.yml @@ -1,69 +1,29 @@ --- # Counterpart of caddy (PLX-Ingress): caddy installs and enables the server; -# this role owns the routing config and runs after it in the platform -# playbook, since the `caddy validate` step needs the binary. - -# Host→port→app is one inventory record per app, so per-VM port uniqueness -# is checkable right here instead of being coordination state (PLX-Ingress). -- name: Assert loopback ports are unique per VM - ansible.builtin.assert: - that: - - plexus_apps | map(attribute='loopback_port') | list | unique | length == plexus_apps | length - fail_msg: "Duplicate loopback port in plexus_apps — each app needs its own loopback_port." - -# A host is one site; the apps on it are told apart by path prefix (PLX-Ingress). -# A prefix is a plain path — leading slash, no trailing slash, no wildcard — -# and each host serves at most one app per prefix, and at most one at its root. -- name: Assert app path prefixes are well-formed - ansible.builtin.assert: - that: - - plexus_apps | selectattr('path', 'defined') | map(attribute='path') | reject('match', '^(/[A-Za-z0-9._~-]+)+$') | list | length == 0 - fail_msg: "apps[].path must look like /name or /a/b — leading slash, no trailing slash, no wildcard." - -- name: Assert each host serves one app per path prefix - ansible.builtin.assert: - that: - - >- - plexus_apps | map(attribute='host') | zip(plexus_apps | map(attribute='path', default='')) - | map('join') | list | unique | length == plexus_apps | length - fail_msg: "Two apps in plexus_apps share a host and a path prefix (or both serve the host's root)." - -# The routes are one file, apps.caddy, rendered from the host's app records; -# a host runs one tenant's apps and nothing else (§ 4 PLX-Tenancy). It lands -# before the root stub so the stub's import resolves when it is validated. -- name: Configure the routes (reverse proxy + automatic HTTPS) - ansible.builtin.template: - src: Caddyfile.j2 - dest: /etc/caddy/apps.caddy - mode: "0644" - validate: "caddy validate --config %s --adapter caddyfile" - notify: Reload caddy - -# Versions before 0.114.0 wrote the routes to tenants/.caddy; the stub -# no longer imports that directory, and a leftover would only confuse. -- name: Remove the per-tenant routing directory of earlier versions - ansible.builtin.file: - path: /etc/caddy/tenants - state: absent - notify: Reload caddy +# this role owns its configuration and runs after it in the platform playbook, +# since validating the configuration needs the binary. +# +# The routes of earlier versions: they rendered every route of the host from +# plexus_apps into /etc/caddy/apps.caddy. This role no longer writes that file +# and never removes it: the root configuration imports it for as long as it is +# there. + +- name: Look for the routes of earlier versions + ansible.builtin.stat: + path: /etc/caddy/apps.caddy + register: ingress_earlier_routes - name: Load Cloudflare's ranges ansible.builtin.include_vars: file: cloudflare.yml when: ingress_trusted_proxies == 'cloudflare' -# No validate: here — ansible validates a temp copy in a temp dir, where the -# stub's relative import glob cannot resolve. The real check is the next task. -- name: Write the root Caddyfile (host-level options, import of the routes) +# Validated as a whole before it replaces the one in place, with every file it +# imports: their paths are absolute, so they resolve from the copy too. +- name: Write the root Caddyfile ansible.builtin.template: src: root.Caddyfile.j2 dest: /etc/caddy/Caddyfile mode: "0644" + validate: caddy validate --config %s --adapter caddyfile notify: Reload caddy - -# Validates the combined config in place, root stub plus routes, before the -# reload handler fires at end of play. -- name: Validate the assembled Caddy config - ansible.builtin.command: - cmd: caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile - changed_when: false diff --git a/ansible/platform/roles/ingress/templates/Caddyfile.j2 b/ansible/platform/roles/ingress/templates/Caddyfile.j2 deleted file mode 100644 index 244c4139..00000000 --- a/ansible/platform/roles/ingress/templates/Caddyfile.j2 +++ /dev/null @@ -1,61 +0,0 @@ -# Managed by Ansible (plexus.platform.ingress) — one route per app record on this host. -# Imported by /etc/caddy/Caddyfile. -# Caddy obtains + renews Let's Encrypt certs automatically for each host -# below (needs DNS → this host and ports 80/443 open). -# One site per host: apps sharing a host each take a path prefix (`path:` in -# the inventory record); an app without one serves the host's root. The -# prefix is stripped before the request reaches the app, so the app serves -# from its own root and learns its public URL from its environment. -# -# /healthz is refused from outside, for every app, root and prefixed alike: -# defence in depth for apps whose healthcheck answers on that conventional -# path, which publicly would tell anyone whether the app's dependencies are -# up. The deploy does not depend on it; it reads the container's health from -# Docker on the host. -{% for host, apps in plexus_apps | groupby('host') %} -{{ host }} { - encode zstd gzip -{% for app in apps %} -{% if app.path is defined %} - # {{ app.name }}{% if app.environment is defined %} ({{ app.environment }}){% endif %}, under {{ app.path }}/ - redir {{ app.path }} {{ app.path }}/ - handle_path {{ app.path }}/* { -{% else %} - # {{ app.name }}{% if app.environment is defined %} ({{ app.environment }}){% endif %} - - handle { -{% endif %} - respond /healthz 403 - reverse_proxy 127.0.0.1:{{ app.loopback_port }} - } -{% endfor %} -{% if apps | selectattr('path', 'undefined') | list | length == 0 %} - # No app serves this host's root. - handle { - respond 404 - } -{% endif %} - # Backend unreachable (deploy rollout, crash, migration window): serve a - # plain maintenance page instead of a bare 502. Auto-refreshes; Retry-After - # keeps well-behaved clients polling. Tenants override the copy via - # ingress_maintenance_lang / _title / _text in their inventory. - handle_errors { - @backend_down expression `{err.status_code} in [502, 503, 504]` - handle @backend_down { - header Retry-After 120 - header Content-Type "text/html; charset=utf-8" - respond < - - - {{ ingress_maintenance_title | default('Back in a minute') }} - -
-

{{ ingress_maintenance_title | default('Back in a minute') }}

-

{{ ingress_maintenance_text | default('This service is briefly unavailable for maintenance. This page refreshes automatically.') }}

-
- MAINTENANCE 503 - } - } -} -{% endfor %} diff --git a/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 b/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 index a79a69a5..8f7b8c32 100644 --- a/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 +++ b/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 @@ -1,5 +1,4 @@ -# Managed by Ansible (plexus.platform.ingress). The routes live in apps.caddy, -# rendered from this host's app records; the options below are host-level +# Managed by Ansible (plexus.platform.ingress). The options below are host-level # (what sits in front of this VM). {% set trusted = ingress_cloudflare_ranges if ingress_trusted_proxies == 'cloudflare' else ingress_trusted_proxies %} {% if ingress_proxy_protocol_from or trusted %} @@ -24,4 +23,9 @@ } } {% endif %} -import apps.caddy +{% if ingress_earlier_routes.stat.exists %} + +# The routes earlier versions rendered from the inventory's records, left as +# they were until removed by hand. +import /etc/caddy/apps.caddy +{% endif %} diff --git a/ansible/platform/roles/secrets/handlers/main.yml b/ansible/platform/roles/secrets/handlers/main.yml deleted file mode 100644 index 619f13ac..00000000 --- a/ansible/platform/roles/secrets/handlers/main.yml +++ /dev/null @@ -1,22 +0,0 @@ ---- -# Rotation closes inside the playbook (§ 2 PLX-Secrets): environment is -# injected at container creation, so a rewritten .env.secret rotates a file, -# not a credential, until the affected containers are re-created. A bare -# `up -d` — the same invocation the deploy verb and a human use, since compose -# reads .env implicitly and the image is pinned in the file — re-creates -# exactly the services whose environment differs. Skipped where the deploy -# verb has not placed a compose file yet, and in check mode, where a new -# deployment's dir does not exist yet and the command would fail on chdir -# before it could skip itself. An app the apps role failed to start is left -# out: the same `up -d` would only fail again, and the playbook reports it. -- name: Re-create app containers for rotated secrets - ansible.builtin.command: - cmd: docker compose up -d - chdir: "{{ item }}" - loop: "{{ secrets_dirs | default([]) | difference(apps_failures | default([]) | map(attribute='dir') | list) }}" - become: true - become_user: "{{ plexus_deploy_user }}" - when: plexus_up | bool and not ansible_check_mode - register: secrets_recreate - changed_when: "'Recreated' in secrets_recreate.stderr or 'Started' in secrets_recreate.stderr" - failed_when: (secrets_recreate.rc | default(1)) != 0 and 'no configuration file' not in (secrets_recreate.stderr | default('')) diff --git a/ansible/platform/roles/secrets/tasks/app.yml b/ansible/platform/roles/secrets/tasks/app.yml deleted file mode 100644 index 0121c9e0..00000000 --- a/ansible/platform/roles/secrets/tasks/app.yml +++ /dev/null @@ -1,46 +0,0 @@ ---- -# The deployment's slug (§ 3 PLX-Platform): -, in every -# environment, as the apps role lays it out. -- name: "{{ app.name }} | resolve the deployment slug" - ansible.builtin.set_fact: - secrets_slug: "{{ app.name ~ '-' ~ app.environment }}" - -- name: "{{ app.name }} | resolve app dir" - ansible.builtin.set_fact: - secrets_dir: "{{ plexus_deploy_root }}/{{ secrets_slug }}" - -# The app dir is laid out by apps (§ 3 PLX-Platform); this role runs -# before it so that the first `up` already sees the secrets, and creates the -# dir identically when it is first here. -- name: "{{ app.name }} | create app dir" - ansible.builtin.file: - path: "{{ secrets_dir }}" - state: directory - owner: "{{ plexus_deploy_user }}" - group: "{{ plexus_deploy_user }}" - mode: "0750" - -# Substance stays on the host: per-app secrets from the tenant's `app.secrets` -# dict — op:// pointers, resolved from the vault here via the 1Password CLI -# the playbook wrapper already runs under — injected into the container by the -# app's compose `env_file`. Never world-readable. Three files in the app dir, -# one writer each (§ 3 PLX-Platform): this role owns .env.secret. -- name: "{{ app.name }} | write .env.secret (vault-resolved secrets)" - ansible.builtin.copy: - dest: "{{ secrets_dir }}/.env.secret" - content: | - # Written by the platform playbook from the tenant inventory, apps[].secrets, - # resolved from the vault (PLX-Secrets). Do not edit. - {% for key, ref in app.secrets.items() %} - {{ key }}={{ lookup('ansible.builtin.pipe', 'op read ' ~ (ref | quote)) }} - {% endfor %} - owner: "{{ plexus_deploy_user }}" - group: "{{ plexus_deploy_user }}" - mode: "0600" - when: app.secrets is defined - no_log: true - notify: Re-create app containers for rotated secrets - -- name: "{{ app.name }} | remember the app dir for the rotation handler" - ansible.builtin.set_fact: - secrets_dirs: "{{ (secrets_dirs | default([])) + [secrets_dir] }}" diff --git a/ansible/platform/roles/secrets/tasks/main.yml b/ansible/platform/roles/secrets/tasks/main.yml deleted file mode 100644 index d011b96f..00000000 --- a/ansible/platform/roles/secrets/tasks/main.yml +++ /dev/null @@ -1,30 +0,0 @@ ---- -# Secrets are vault references, never values (PLX-Secrets): every entry of -# apps[].secrets is an op:// pointer, resolved below at playbook time. -- name: Assert app secrets are op:// pointers - ansible.builtin.assert: - that: - - >- - plexus_apps | map(attribute='secrets', default={}) | map('dict2items') | flatten - | map(attribute='value') | reject('match', '^op://') | list | length == 0 - fail_msg: "Every apps[].secrets value must be an op://vault/item/field pointer (PLX-Secrets) — values never live in git." - -# The app dir is named - (app.yml); this role runs before -# apps in the platform playbook, so it holds the records to that first. The -# apps role has the same check: each role stands alone, and one shared check -# would make one of them include a task file of the other. -- name: Assert every app record names its environment - ansible.builtin.assert: - that: - - plexus_apps | rejectattr('environment', 'defined') | list | length == 0 - fail_msg: >- - {% set missing = plexus_apps | rejectattr('environment', 'defined') | map(attribute='name', default='?') | list -%} - plexus_apps: the record{{ 's' if missing | length > 1 else '' }} '{{ missing | join("', '") }}' - name{{ '' if missing | length > 1 else 's' }} no environment; every record names one, for example environment: production - -- name: Write each app's secrets - ansible.builtin.include_tasks: app.yml - loop: "{{ plexus_apps }}" - loop_control: - loop_var: app - label: "{{ app.name }}" diff --git a/tests/all-roles.yml b/tests/all-roles.yml index 3158898c..f4b55397 100644 --- a/tests/all-roles.yml +++ b/tests/all-roles.yml @@ -20,9 +20,7 @@ - plexus.infrastructure.haproxy - plexus.infrastructure.pbs - plexus.infrastructure.proxmox - - plexus.platform.apps - plexus.platform.caddy - plexus.platform.deploy_user - plexus.platform.ingress - - plexus.platform.secrets - plexus.platform.stack From 0fc049750cd1ec282bf310d7e640fe8da9af5744 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:48:14 +0100 Subject: [PATCH 09/91] test: the platform playbook prepares a fresh host for stacks On a host without records: /opt/stacks is the deploy user's, the deploy user writes a route fragment that the proxy serves after a reload, and a second run changes nothing. Red: no deploy root, no fragment directory. Co-Authored-By: Claude Opus 5.5 --- tests/platform-playbook.sh | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh index 53182852..ef5e4acb 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -117,7 +117,7 @@ on() { docker exec "$run-$1" "${@:2}"; } as() { docker exec -u "$1" "$run-$2" "${@:3}"; } # get : the status and body of a request the proxy serves on the host. get() { on "$1" curl -s -m 5 -w ' %{http_code}' -H "Host: $2" "http://127.0.0.1$3" || true; } -# backend : a service on 127.0.0.1: of the host that answers every path with . +# backend : a service on 127.0.0.1: of the host that answers / and /healthz with . backend() { on "$1" sh -c "mkdir -p /srv/$2 && printf %s '$3' >/srv/$2/index.html && cp /srv/$2/index.html /srv/$2/healthz" on "$1" systemd-run -q --unit "backend-$2" python3 -m http.server -b 127.0.0.1 -d "/srv/$2" "$2" @@ -128,6 +128,26 @@ snapshot() { on "$1" sh -c 'find "$@" -exec stat -c "%n %U:%G %a %s %Y" {} + | sort; find "$@" -type f -exec sha256sum {} + | sort' - "${@:2}" } +# fragment : a route fragment, written by the deploy user as the stack playbook writes one. +fragment() { printf '%s\n' "$3" | docker exec -i -u plexus "$run-$1" sh -c "cat >/etc/caddy/stacks/$2"; } + +case='a fresh host' +host fresh +play fresh +[ "$status" = 0 ] || fail "exit code $status" +! grep -q '"msg": "plexus_apps is no longer read' "$work/out" || fail "a message about plexus_apps" +[ "$(on fresh stat -c '%U:%G %a' /opt/stacks)" = 'plexus:plexus 755' ] || fail "/opt/stacks is not the deploy user's" +as plexus fresh sh -c 'mkdir /opt/stacks/probe && rmdir /opt/stacks/probe' || fail "the deploy user cannot write /opt/stacks" +fragment fresh shop-staging.caddy 'http://shop.example.com { + respond "from a fragment" +}' +on fresh systemctl reload caddy || fail "the proxy does not reload with a fragment" +[ "$(get fresh shop.example.com /)" = 'from a fragment 200' ] || fail "the fragment's route is not served" +play fresh +[ "$status" = 0 ] || fail "exit code $status, second run" +grep -q '^fresh *: ok=[0-9]* *changed=0 ' "$work/out" || fail "a second run changed something" +echo "✓ $case" + case='a host that carries deployments of an earlier version' host migrated # As the earlier platform playbook left it: the deployment's directory with its @@ -175,7 +195,7 @@ EOF before=$(snapshot migrated /opt/stacks/shop-production /etc/caddy/apps.caddy) play migrated [ "$status" = 0 ] || fail "exit code $status" -grep -q 'plexus_apps is no longer read' "$work/out" || fail "no message that plexus_apps is no longer read" +grep -q '"msg": "plexus_apps is no longer read' "$work/out" || fail "no message that plexus_apps is no longer read" [ "$(snapshot migrated /opt/stacks/shop-production /etc/caddy/apps.caddy)" = "$before" ] || fail "a deployment's file or apps.caddy changed" [ -z "$(on migrated cat /var/log/docker-calls 2>/dev/null)" ] || fail "docker was run: $(on migrated cat /var/log/docker-calls)" [ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the deployment's route no longer answers" From 690ee494161c960d01482705293f599e7d3f6c1a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:49:18 +0100 Subject: [PATCH 10/91] The platform playbook gives the deploy user the deploy root and the route fragments deploy_user creates /opt/stacks (plexus_deploy_root) owned by the deploy user, 0750; the test now expects that mode. ingress creates ingress_fragments_dir, /etc/caddy/stacks, owned by the deploy user, and the root Caddyfile imports every *.caddy in it. Neither recurses. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/roles/deploy_user/defaults/main.yml | 5 ++++- ansible/platform/roles/deploy_user/tasks/main.yml | 9 +++++++++ ansible/platform/roles/ingress/defaults/main.yml | 5 +++++ ansible/platform/roles/ingress/tasks/main.yml | 9 +++++++++ .../platform/roles/ingress/templates/root.Caddyfile.j2 | 3 +++ tests/platform-playbook.sh | 2 +- 6 files changed, 31 insertions(+), 2 deletions(-) diff --git a/ansible/platform/roles/deploy_user/defaults/main.yml b/ansible/platform/roles/deploy_user/defaults/main.yml index 58ff1698..90879864 100644 --- a/ansible/platform/roles/deploy_user/defaults/main.yml +++ b/ansible/platform/roles/deploy_user/defaults/main.yml @@ -1,10 +1,13 @@ --- # The unprivileged user that owns the deploy root and as which the stack -# playbook deploys over SSH. The plexus_ variables are shared with other roles +# playbook deploys over SSH; the role creates both, and changes nothing below +# the root. The plexus_ variables are shared with other roles # (plexus.host.docker adds the user to the docker group), so they keep that # prefix and have no default here; set them in the operations repo's group # variables: # plexus_deploy_user the user's name +# plexus_deploy_root the directory the user owns, under which each +# environment of a stack has its own; unset: /opt/stacks # plexus_deploy_pubkey the public key the deployer connects with; unset or # empty: no key is authorized # plexus_ghcr_user the registry login the user pulls the stacks' images diff --git a/ansible/platform/roles/deploy_user/tasks/main.yml b/ansible/platform/roles/deploy_user/tasks/main.yml index 6bd1fa9b..0f878e8d 100644 --- a/ansible/platform/roles/deploy_user/tasks/main.yml +++ b/ansible/platform/roles/deploy_user/tasks/main.yml @@ -7,6 +7,15 @@ groups: "{{ deploy_user_groups }}" append: true +# Not recursive: what lies below is the stack playbook's. +- name: Give the deploy user the deploy root + ansible.builtin.file: + path: "{{ plexus_deploy_root | default('/opt/stacks') }}" + state: directory + owner: "{{ plexus_deploy_user }}" + group: "{{ plexus_deploy_user }}" + mode: "0750" + - name: Authorize the deploy key (the stack playbook connects as this user) ansible.posix.authorized_key: user: "{{ plexus_deploy_user }}" diff --git a/ansible/platform/roles/ingress/defaults/main.yml b/ansible/platform/roles/ingress/defaults/main.yml index c3c1f2a8..a35275cf 100644 --- a/ansible/platform/roles/ingress/defaults/main.yml +++ b/ansible/platform/roles/ingress/defaults/main.yml @@ -1,4 +1,9 @@ --- +# Where the stacks' routes live: one file per environment that has a hostname, +# -.caddy, written by the stack playbook as the deploy +# user, who owns the directory; the root Caddyfile imports every *.caddy in it. +ingress_fragments_dir: /etc/caddy/stacks + # Host-level settings of the Caddy server, rendered into the root Caddyfile. # They describe what sits in front of the host, so every tenant co-hosted on # the VM has to set them identically (§ 4 PLX-Tenancy keeps that to one tenant). diff --git a/ansible/platform/roles/ingress/tasks/main.yml b/ansible/platform/roles/ingress/tasks/main.yml index 0bff6299..7992a33c 100644 --- a/ansible/platform/roles/ingress/tasks/main.yml +++ b/ansible/platform/roles/ingress/tasks/main.yml @@ -13,6 +13,15 @@ path: /etc/caddy/apps.caddy register: ingress_earlier_routes +# Not recursive: the fragments in it are the stack playbook's. +- name: Give the deploy user the directory of route fragments + ansible.builtin.file: + path: "{{ ingress_fragments_dir }}" + state: directory + owner: "{{ plexus_deploy_user }}" + group: "{{ plexus_deploy_user }}" + mode: "0755" + - name: Load Cloudflare's ranges ansible.builtin.include_vars: file: cloudflare.yml diff --git a/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 b/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 index 8f7b8c32..630ff7fe 100644 --- a/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 +++ b/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 @@ -29,3 +29,6 @@ # they were until removed by hand. import /etc/caddy/apps.caddy {% endif %} + +# The stacks' routes, one fragment per environment, written by the stack playbook. +import {{ ingress_fragments_dir }}/*.caddy diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh index ef5e4acb..aa11a2d5 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -136,7 +136,7 @@ host fresh play fresh [ "$status" = 0 ] || fail "exit code $status" ! grep -q '"msg": "plexus_apps is no longer read' "$work/out" || fail "a message about plexus_apps" -[ "$(on fresh stat -c '%U:%G %a' /opt/stacks)" = 'plexus:plexus 755' ] || fail "/opt/stacks is not the deploy user's" +[ "$(on fresh stat -c '%U:%G %a' /opt/stacks)" = 'plexus:plexus 750' ] || fail "/opt/stacks is not the deploy user's" as plexus fresh sh -c 'mkdir /opt/stacks/probe && rmdir /opt/stacks/probe' || fail "the deploy user cannot write /opt/stacks" fragment fresh shop-staging.caddy 'http://shop.example.com { respond "from a fragment" From b40e949ae1a4e14cdca9a13b97b06d6a02c44ea3 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:50:00 +0100 Subject: [PATCH 11/91] test: the deploy user reloads the proxy by one sudo rule and nothing else As the deploy user, sudo -n /usr/bin/systemctl reload caddy reloads the proxy with a changed fragment; sudo lists one rule; restart, another unit, extra arguments, another target user and a shell are refused; the host's sudo rules pass visudo -c. Red: there is no rule. Co-Authored-By: Claude Opus 5.5 --- tests/platform-playbook.sh | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh index aa11a2d5..57859320 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -148,6 +148,23 @@ play fresh grep -q '^fresh *: ok=[0-9]* *changed=0 ' "$work/out" || fail "a second run changed something" echo "✓ $case" +case='the one sudo rule of the deploy user' +fragment fresh shop-staging.caddy 'http://shop.example.com { + respond "reloaded by the deploy user" +}' +as plexus fresh sudo -n /usr/bin/systemctl reload caddy || fail "the deploy user cannot reload the proxy" +[ "$(get fresh shop.example.com /)" = 'reloaded by the deploy user 200' ] || fail "the reload did not take the fragment" +[ "$(as plexus fresh sudo -n -l | grep -c '^ *(')" = 1 ] || fail "the deploy user has more than one rule: $(as plexus fresh sudo -n -l)" +denied() { ! as plexus fresh sudo -n -l "$@" >/dev/null 2>&1 || fail "the deploy user may run sudo $*"; } +denied /usr/bin/systemctl restart caddy +denied /usr/bin/systemctl reload caddy.service +denied /usr/bin/systemctl reload ssh +denied /usr/bin/systemctl reload caddy ssh +denied -u caddy /usr/bin/systemctl reload caddy +denied /bin/sh +on fresh visudo -c >/dev/null || fail "visudo -c finds an error in the host's sudo rules" +echo "✓ $case" + case='a host that carries deployments of an earlier version' host migrated # As the earlier platform playbook left it: the deployment's directory with its From 33200d295438331639a0e2854c6bfbc71abe1f30 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:50:55 +0100 Subject: [PATCH 12/91] The deploy user may reload the proxy, and nothing else ingress writes /etc/sudoers.d/reload-caddy, validated with visudo -cf: ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/roles/ingress/tasks/main.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/ansible/platform/roles/ingress/tasks/main.yml b/ansible/platform/roles/ingress/tasks/main.yml index 7992a33c..5ab896eb 100644 --- a/ansible/platform/roles/ingress/tasks/main.yml +++ b/ansible/platform/roles/ingress/tasks/main.yml @@ -22,6 +22,21 @@ group: "{{ plexus_deploy_user }}" mode: "0755" +# The deploy user's one privilege: one command, its arguments matched exactly, +# as root. Ansible's become cannot use it (it wraps every command in a shell); +# the stack playbook runs `sudo -n /usr/bin/systemctl reload caddy` as a +# command of its own. +- name: Let the deploy user reload the proxy, and do nothing else as root + ansible.builtin.copy: + dest: /etc/sudoers.d/reload-caddy + content: | + # Managed by Ansible (plexus.platform.ingress). + {{ plexus_deploy_user }} ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy + owner: root + group: root + mode: "0440" + validate: visudo -cf %s + - name: Load Cloudflare's ranges ansible.builtin.include_vars: file: cloudflare.yml From d5b4621d6f13bfaafbac654646ac5713c368db42 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:51:31 +0100 Subject: [PATCH 13/91] test: a stack's route takes the fence and the maintenance page from the root A fragment of the form { import stack } reaches the stack on its loopback port, /healthz is refused although the stack answers it, and a port where nothing answers gets the maintenance page. Red: the root configuration defines no snippet stack. Co-Authored-By: Claude Opus 5.5 --- tests/platform-playbook.sh | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh index 57859320..d409e6ee 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -165,6 +165,23 @@ denied /bin/sh on fresh visudo -c >/dev/null || fail "visudo -c finds an error in the host's sudo rules" echo "✓ $case" +case="a stack's route: to its port, /healthz refused, a maintenance page while nothing answers" +# A fragment names the hostname and the loopback port, and imports the rest +# from the root configuration: the stack playbook writes no more than that. +backend fresh 20001 'shop staging' +fragment fresh shop-staging.caddy 'http://shop.example.com { + import stack 20001 +}' +fragment fresh shop-preview.caddy 'http://preview.shop.example.com { + import stack 20002 +}' +as plexus fresh sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload" +[ "$(get fresh shop.example.com /)" = 'shop staging 200' ] || fail "the route does not reach the stack: $(get fresh shop.example.com /)" +[ "$(on fresh curl -s -m 5 http://127.0.0.1:20001/healthz)" = 'shop staging' ] || fail "the stack does not answer /healthz itself" +[ "$(get fresh shop.example.com /healthz)" = ' 403' ] || fail "/healthz is not refused: $(get fresh shop.example.com /healthz)" +[[ $(get fresh preview.shop.example.com /) == *'Back in a minute'*' 503' ]] || fail "no maintenance page where nothing answers" +echo "✓ $case" + case='a host that carries deployments of an earlier version' host migrated # As the earlier platform playbook left it: the deployment's directory with its From ce28dce0f5aba4f6367d6259a002d53c8e5d06cd Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:52:33 +0100 Subject: [PATCH 14/91] The root Caddyfile states what every stack's route does but its name and port The snippet stack encodes, refuses /healthz, proxies to 127.0.0.1 on the port it is given, and serves the maintenance page while the stack does not answer; a fragment is { import stack }. The maintenance page's variables get their defaults in the role's defaults. Co-Authored-By: Claude Opus 5.5 --- .../platform/roles/ingress/defaults/main.yml | 6 ++++ .../roles/ingress/templates/root.Caddyfile.j2 | 36 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/ansible/platform/roles/ingress/defaults/main.yml b/ansible/platform/roles/ingress/defaults/main.yml index a35275cf..26821a70 100644 --- a/ansible/platform/roles/ingress/defaults/main.yml +++ b/ansible/platform/roles/ingress/defaults/main.yml @@ -4,6 +4,12 @@ # user, who owns the directory; the root Caddyfile imports every *.caddy in it. ingress_fragments_dir: /etc/caddy/stacks +# The maintenance page a stack's route serves while the stack does not +# answer: its language, title and text. +ingress_maintenance_lang: en +ingress_maintenance_title: Back in a minute +ingress_maintenance_text: This service is briefly unavailable for maintenance. This page refreshes automatically. + # Host-level settings of the Caddy server, rendered into the root Caddyfile. # They describe what sits in front of the host, so every tenant co-hosted on # the VM has to set them identically (§ 4 PLX-Tenancy keeps that to one tenant). diff --git a/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 b/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 index 630ff7fe..c096a0c3 100644 --- a/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 +++ b/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 @@ -23,6 +23,42 @@ } } {% endif %} + +# What every stack's route does but its hostname and port, stated here once. A +# route fragment is exactly +# { +# import stack +# } +# /healthz is refused from outside, for every stack: defence in depth for +# stacks whose healthcheck answers on that conventional path, which publicly +# would tell anyone whether their dependencies are up. The deploy does not +# depend on it; it reads the containers' health from Docker on the host. +# Where the stack does not answer (a deploy, a crash, a migration), a plain +# maintenance page instead of a bare 502, which refreshes itself; Retry-After +# keeps well-behaved clients polling. +(stack) { + encode zstd gzip + respond /healthz 403 + reverse_proxy 127.0.0.1:{args[0]} + handle_errors { + @backend_down expression `{err.status_code} in [502, 503, 504]` + handle @backend_down { + header Retry-After 120 + header Content-Type "text/html; charset=utf-8" + respond < + + + {{ ingress_maintenance_title }} + +
+

{{ ingress_maintenance_title }}

+

{{ ingress_maintenance_text }}

+
+ MAINTENANCE 503 + } + } +} {% if ingress_earlier_routes.stat.exists %} # The routes earlier versions rendered from the inventory's records, left as From 6d6febe5340b9a46c99dd4898523c979aafc7d7b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:53:35 +0100 Subject: [PATCH 15/91] test: the old routes and the fragments coexist while a host migrates A fragment beside apps.caddy is served with the old routes; one for a hostname apps.caddy still serves is refused by the proxy, which goes on serving the old route; once the block is out of apps.caddy the hostname moves to its fragment; once apps.caddy is deleted, reloads work before and after the next platform run. Red: the root imports apps.caddy by its path, and a reload fails once it is gone. Co-Authored-By: Claude Opus 5.5 --- tests/platform-playbook.sh | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh index d409e6ee..a4b61a4c 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -236,3 +236,36 @@ grep -q '"msg": "plexus_apps is no longer read' "$work/out" || fail "no message on migrated systemctl reload caddy || fail "the proxy does not reload" [ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the deployment's route no longer answers after a reload" echo "✓ $case" + +case='a host in migration: the old routes beside the fragments' +# A stack's environment gets a fragment while the old routes are still there. +backend migrated 20001 'shop staging' +fragment migrated shop-staging.caddy 'http://staging.shop.example.com { + import stack 20001 +}' +as plexus migrated sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload with a fragment beside the old routes" +[ "$(get migrated staging.shop.example.com /)" = 'shop staging 200' ] || fail "the fragment's route is not served" +[ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the old route is no longer served" +# A fragment for a hostname the old routes still serve: the proxy refuses the +# configuration and goes on serving the old route. +backend migrated 20002 'shop production, by its fragment' +fragment migrated shop-production.caddy 'http://shop.example.com { + import stack 20002 +}' +! as plexus migrated sudo -n /usr/bin/systemctl reload caddy 2>/dev/null || fail "the proxy took one hostname twice" +[ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the old route is no longer served after a refused reload" +# The person's step: the hostname's block out of apps.caddy; the next reload +# moves the hostname to its fragment. +on migrated sed -i '/^http:\/\/shop\.example\.com {$/,/^}$/d' /etc/caddy/apps.caddy +as plexus migrated sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload once the old route is out" +[ "$(get migrated shop.example.com /)" = 'shop production, by its fragment 200' ] || fail "the hostname did not move to its fragment" +# Once every route has its fragment, apps.caddy goes; reloads go on working, +# before and after the next run of the platform playbook. +on migrated rm /etc/caddy/apps.caddy +as plexus migrated sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload once apps.caddy is gone" +play migrated +[ "$status" = 0 ] || fail "exit code $status" +as plexus migrated sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload after the platform playbook" +[ "$(get migrated shop.example.com /)" = 'shop production, by its fragment 200' ] || fail "the route is not served" +[ "$(get migrated staging.shop.example.com /)" = 'shop staging 200' ] || fail "the route is not served" +echo "✓ $case" From 4f3c495f90ecb3832b76c26ac5239e95df499550 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:54:09 +0100 Subject: [PATCH 16/91] Test: the whole compose document is read for required variables, and only .env covers them Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.test.ts | 61 +++++++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index d7587fca..7a065993 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -2353,7 +2353,6 @@ ${SITE_SERVICES} ports: ["127.0.0.1:\${PLEXUS_LOOPBACK_PORT:?set}:3000"] REGION: \${REGION:-eu} SHA: \${PLEXUS_COMMIT_SHA:-} PROJECT: \${COMPOSE_PROJECT_NAME} - TOKEN: \${API_TOKEN:?the token} ESCAPED: $\${NOT_A_VARIABLE} `; const PRODUCTION = @@ -2422,8 +2421,8 @@ test("a variable the compose file requires that an environment lists nowhere fai }), ); assert.deepEqual(missing.sort(), [ - 'compose.yaml requires `MODE`, which production.yaml lists under neither `env` nor `secrets`', - 'compose.yaml requires `MODE`, which staging.yaml lists under neither `env` nor `secrets`', + 'compose.yaml requires `MODE`, which production.yaml does not list under `env`', + 'compose.yaml requires `MODE`, which staging.yaml does not list under `env`', ]); const alone = await environmentFindings( environmentFiles({ @@ -2435,14 +2434,19 @@ test("a variable the compose file requires that an environment lists nowhere fai assert.deepEqual(alone, []); }); -test('a variable listed under secrets covers the compose file as one under env does', async () => { +test('a variable the compose file requires and an environment lists only under secrets is not covered: compose fills it from .env', async () => { const swapped = environmentFiles({ 'production.yaml': 'host: 192.0.2.1\nhostname: shop.example.com\nsecrets:\n API_TOKEN: op://a/b/c\n MODE: op://a/b/mode\n', - 'staging.yaml': - 'host: 192.0.2.2\nhostname: s.example.com\nsecrets:\n API_TOKEN: op://a/b/c\n MODE: op://a/b/mode\n', + 'staging.yaml': STAGING, }); - assert.deepEqual(await environmentFindings(swapped), []); + const found = await environmentFindings(swapped); + assert.ok( + found.includes( + 'compose.yaml requires `MODE`, which production.yaml lists under `secrets` only; compose fills `${…}` from `.env`, and a secret reaches a container through `env_file`, so list it under `env`', + ), + found.join('\n'), + ); }); test('a compose file that binds PLEXUS_LOOPBACK_PORT needs a hostname in every environment, and one that does not needs none', async () => { @@ -2459,3 +2463,46 @@ test('a compose file that binds PLEXUS_LOOPBACK_PORT needs a hostname in every e 'staging.yaml has a `hostname`, but compose.yaml binds no `PLEXUS_LOOPBACK_PORT`, so the environment gets no port and no route', ]); }); + +/** The variables the compose file requires, as production.yaml is told, over the compose file `text`. */ +async function requiredBy(text: string): Promise { + const found = await environmentFindings(environmentFiles({ 'compose.yaml': text })); + return found.flatMap((p) => /^compose\.yaml requires `(\w+)`, which production\.yaml/.exec(p)?.[1] ?? []).sort(); +} +const ENV_ONLY = FROM_ENV.replace(/ {6}MODE: .*\n/, ''); + +test('every value of the compose file is read for the variables it requires, as compose reads it: top-level volumes, networks, x- fields and lists, not keys', async () => { + const extra = ` extra: + image: postgres:16 + command: ["run", "\${IN_LIST}"] + environment: + BARE: $BARE_VARIABLE + labels: + "\${IN_KEY}": value +x-note: \${IN_X_FIELD} +volumes: + data: + name: \${IN_VOLUME} +networks: + back: + name: \${IN_NETWORK} +`; + const needed = await requiredBy(compose(ENV_ONLY.replace(/ {4}environment:\n$/, '')) + extra); + assert.deepEqual(needed, ['BARE_VARIABLE', 'IN_LIST', 'IN_NETWORK', 'IN_VOLUME', 'IN_X_FIELD']); +}); + +test('a variable with a default or an alternative is not required, in any of the four forms; one with an error message is', async () => { + const extra = ` extra: + image: postgres:16 + environment: + A: \${DEFAULT_DASH-x} + B: \${DEFAULT_COLON_DASH:-x} + C: \${ALT_PLUS+x} + D: \${ALT_COLON_PLUS:+x} + E: \${MESSAGE:?say} + F: \${MESSAGE_PLAIN?say} + G: \${PLAIN} +`; + const needed = await requiredBy(compose(ENV_ONLY.replace(/ {4}environment:\n$/, '')) + extra); + assert.deepEqual(needed, ['MESSAGE', 'MESSAGE_PLAIN', 'PLAIN']); +}); From e19dbc35df6d9f220e4c0344ba2017819e0c90b0 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:54:33 +0100 Subject: [PATCH 17/91] Required variables are read from the whole compose document and covered by env alone Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/compose.ts | 4 +++- packages/lib/src/doctor.ts | 10 ++++++---- packages/lib/src/environments.ts | 13 +++++-------- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/packages/lib/src/compose.ts b/packages/lib/src/compose.ts index 15eb5af3..6bb0ce6b 100644 --- a/packages/lib/src/compose.ts +++ b/packages/lib/src/compose.ts @@ -21,6 +21,8 @@ import { UsageError } from './version.ts'; export type Mapping = Record; export interface Compose { + /** The whole document as parsed, anchors and merge keys resolved, interpolation as written; what interpolation is read from. */ + document: unknown; /** The services by name, same-file `extends` merged in; an entry that is not a mapping is left out. */ services: Record; /** The file has a top-level `include`, whose files are not read. */ @@ -45,7 +47,7 @@ export function parseCompose(text: string, path: string): Compose { const written: Record = {}; for (const [name, service] of Object.entries(declared)) if (isMapping(service)) written[name] = service; const services = resolveExtends(written, path); - return { services, ...(isMapping(doc) && doc.include != null ? { includes: true as const } : {}) }; + return { document: doc, services, ...(isMapping(doc) && doc.include != null ? { includes: true as const } : {}) }; } /** diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 6a030631..44db8d66 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -514,8 +514,8 @@ export const CHECKS: Readonly> * `problems`, one line each); the files list the same names under `env` and * the same names under `secrets`, one line for each name an environment * lacks, naming the first that has it; every variable the compose file - * requires by interpolation (`requiredVariables`) is listed under `env` or - * `secrets` of each, but for the platform's (`PLATFORM_VARIABLES`); and an + * requires by interpolation (`requiredVariables`) is listed under `env` of + * each (compose fills `${…}` from `.env` alone), but for the platform's (`PLATFORM_VARIABLES`); and an * environment has a `hostname` exactly where the compose file binds * `PLEXUS_LOOPBACK_PORT`, as the environment gets a port and a route only then. */ @@ -534,9 +534,11 @@ function environmentFindings(stack: StackFacts): string[] { if (compose && environments.length > 0) { for (const variable of requiredVariables(compose).filter((v) => !PLATFORM_VARIABLES.includes(v))) for (const e of environments) - if (!(variable in e.env) && !(variable in e.secrets)) + if (!(variable in e.env)) problems.push( - `compose.yaml requires \`${variable}\`, which ${e.name}.yaml lists under neither \`env\` nor \`secrets\``, + variable in e.secrets + ? `compose.yaml requires \`${variable}\`, which ${e.name}.yaml lists under \`secrets\` only; compose fills \`\${…}\` from \`.env\`, and a secret reaches a container through \`env_file\`, so list it under \`env\`` + : `compose.yaml requires \`${variable}\`, which ${e.name}.yaml does not list under \`env\``, ); const binds = Object.values(compose.services).some((service) => portsOf(service).some(bindsLoopbackVar)); for (const e of environments) { diff --git a/packages/lib/src/environments.ts b/packages/lib/src/environments.ts index 7e53fb80..1319c964 100644 --- a/packages/lib/src/environments.ts +++ b/packages/lib/src/environments.ts @@ -25,8 +25,9 @@ // environment to give: those it interpolates without a default (`${NAME}`, // `$NAME`, `${NAME:?message}`, `${NAME?message}`), not the ones with a // default or an alternative (`${NAME:-x}`, `${NAME-x}`, `${NAME:+x}`, -// `${NAME+x}`); `$$` is compose's escape and no variable. It reads every string -// of the services, keys included. The variables the platform supplies itself +// `${NAME+x}`); `$$` is compose's escape and no variable. It reads every value of the +// document, as compose does (services, top-level `volumes` and `networks`, +// `x-` fields, lists), and no key. The variables the platform supplies itself // (`PLATFORM_VARIABLES`) are among them where the file uses them, and are // listed in no environment file. import { join } from 'node:path'; @@ -143,12 +144,8 @@ export function requiredVariables(compose: Compose): string[] { else if (braced !== undefined && !/^:?[-+]/.test(rest ?? '')) found.add(braced); } } else if (Array.isArray(value)) value.forEach(visit); - else if (isMapping(value)) - for (const [key, child] of Object.entries(value)) { - visit(key); - visit(child); - } + else if (isMapping(value)) for (const child of Object.values(value)) visit(child); }; - visit(compose.services); + visit(compose.document); return [...found]; } From 93fd38fd4082bde032c2619ee60f18102f2edc9a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:55:27 +0100 Subject: [PATCH 18/91] Test: one bad value is one finding; env values are strings; more cases are findings Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.test.ts | 52 +++++++++++++++ packages/lib/src/stacks.test.ts | 115 +++++++++++++++++++++++++------- 2 files changed, 143 insertions(+), 24 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 7a065993..86c05f69 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -2506,3 +2506,55 @@ test('a variable with a default or an alternative is not required, in any of the const needed = await requiredBy(compose(ENV_ONLY.replace(/ {4}environment:\n$/, '')) + extra); assert.deepEqual(needed, ['MESSAGE', 'MESSAGE_PLAIN', 'PLAIN']); }); + +test('one bad value in an environment file is one finding: no `lists no` line follows from it', async () => { + const cases: [string, string, string][] = [ + ['an empty file', '', 'staging.yaml: is empty; it needs a `host`'], + ['no YAML', 'host: [\n', 'staging.yaml: not valid YAML: '], + ['no map', '- a\n', 'staging.yaml: is not a map of `host`, `hostname`, `env` and `secrets`'], + [ + 'an env value that is no string', + STAGING.replace('MODE: staging', 'MODE: 3'), + 'staging.yaml: `env` `MODE` is not a string; quote it', + ], + [ + 'a null env value', + STAGING.replace('MODE: staging', 'MODE:'), + 'staging.yaml: `env` `MODE` is not a string; quote it', + ], + [ + 'a secret that is no string', + STAGING.replace('op://acme/shop-staging/token', '3'), + 'staging.yaml: `secrets` `API_TOKEN` is no `op://` pointer', + ], + ]; + for (const [what, text, expected] of cases) { + const found = await environmentFindings(environmentFiles({ 'staging.yaml': text })); + assert.equal(found.length, 1, `${what}: ${found.join('\n')}`); + assert.ok(found[0]?.startsWith(expected), `${what}: ${found[0]}`); + } +}); + +test('a name under both env and secrets, and a name the platform supplies, are findings of the file', async () => { + const both = await environmentFindings( + environmentFiles({ 'staging.yaml': `${STAGING} MODE: op://acme/shop/mode\n` }), + ); + assert.ok(both.includes('staging.yaml: `MODE` is listed under both `env` and `secrets`'), both.join('\n')); + const platform = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace('env:\n', 'env:\n PLEXUS_TAG: x\n') }), + ); + assert.ok( + platform.includes('staging.yaml: `PLEXUS_TAG` is supplied by the platform; remove it'), + platform.join('\n'), + ); +}); + +test('a `.yml` file in a stack directory is a finding of the stack', async () => { + const found = await environmentFindings(environmentFiles({ 'preview.yml': 'host: 192.0.2.3\n' })); + assert.deepEqual(found, ['stack/preview.yml: name it preview.yaml']); +}); + +test('an environment that could not be read is left out of the comparisons with the others', async () => { + const found = await environmentFindings(environmentFiles({ 'staging.yaml': '' })); + assert.equal(found.length, 1, found.join('\n')); +}); diff --git a/packages/lib/src/stacks.test.ts b/packages/lib/src/stacks.test.ts index aee80315..bece0846 100644 --- a/packages/lib/src/stacks.test.ts +++ b/packages/lib/src/stacks.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { Context } from './context.ts'; import { loadStacks } from './stacks.ts'; -import { fakeIo, type Tree } from './testing/fakeIo.ts'; +import { fakeIo, link, type Tree } from './testing/fakeIo.ts'; const compose = (image = 'ghcr.io/acme/shop:${PLEXUS_TAG}') => `services:\n web:\n image: ${image}\n`; const marker = (profile = 'stateless') => `---\nprofile: ${profile}\n---\n\nA stack.\n`; @@ -409,7 +409,7 @@ const environmentsOf = async (files: Tree) => { test("a stack's environments are its `.yaml` files but the compose files, by name, parsed into host, hostname, env and secrets", async () => { const environments = await environmentsOf({ - 'staging.yaml': 'host: 192.0.2.2\nenv:\n MODE: staging\n RETRIES: 3\n DEBUG: true\n', + 'staging.yaml': 'host: 192.0.2.2\nenv:\n MODE: staging\n RETRIES: "3"\n DEBUG: "true"\n', 'production.yaml': 'host: 192.0.2.1\nhostname: shop.example.com\nenv:\n MODE: production\nsecrets:\n TOKEN: op://acme/shop/token\n', 'compose.dev.yaml': 'services: {}\n', @@ -424,6 +424,8 @@ test("a stack's environments are its `.yaml` files but the compose files, hostname: 'shop.example.com', env: { MODE: 'production' }, secrets: { TOKEN: 'op://acme/shop/token' }, + refused: { env: [], secrets: [] }, + unread: false, problems: [], }, { @@ -432,6 +434,8 @@ test("a stack's environments are its `.yaml` files but the compose files, host: '192.0.2.2', env: { MODE: 'staging', RETRIES: '3', DEBUG: 'true' }, secrets: {}, + refused: { env: [], secrets: [] }, + unread: false, problems: [], }, ]); @@ -457,20 +461,45 @@ test('each stack of several has the environments of its own directory', async () ); }); -test('an environment file that cannot be used says why in its own problems, and is still returned', async () => { +test('a directory named like an environment file is no environment', async () => { + assert.deepEqual(await environmentsOf({ 'staging.yaml': { 'host.yaml': 'x' } }), []); +}); + +test('an environment file that cannot be used says why in its own problems, one line per bad value, and is still returned', async () => { const cases: [string, string, RegExp][] = [ - ['staging', 'host: 192.0.2.1\nport: 1\n', /unknown key `port`/], - ['staging', 'hostname: shop.example.com\n', /no `host`/], - ['staging', 'host: 192.0.2.1\nsecrets:\n TOKEN: plain\n', /`TOKEN`.*op:\/\//], - ['staging', 'host: 192.0.2.1\nenv:\n LIST: [a]\n', /`LIST`.*plain value/], - ['staging', 'host: 192.0.2.1\nenv: [a]\n', /`env`.*map/], - ['staging', 'host: 192.0.2.1\nsecrets: x\n', /`secrets`.*map/], - ['staging', 'host: 3\n', /`host`.*string/], - ['staging', 'host: 192.0.2.1\nhostname: 3\n', /`hostname`.*string/], - ['staging', '- a\n', /map/], - ['staging', 'host: [\n', /not valid YAML/], + ['staging', 'host: 192.0.2.1\nport: 1\n', /staging\.yaml: unknown key `port`/], + ['staging', 'hostname: shop.example.com\n', /staging\.yaml: has no `host`/], + ['staging', 'host: ""\n', /staging\.yaml: `host` is not a non-empty string/], + ['staging', 'host: 3\n', /`host` is not a non-empty string/], + ['staging', 'host: 192.0.2.1\nhostname: 3\n', /`hostname` is not a non-empty string/], + ['staging', 'host: 192.0.2.1\nsecrets:\n TOKEN: plain\n', /`secrets` `TOKEN` is no `op:\/\/` pointer/], + ['staging', 'host: 192.0.2.1\nsecrets:\n TOKEN: 3\n', /`secrets` `TOKEN` is no `op:\/\/` pointer/], + ['staging', 'host: 192.0.2.1\nenv: [a]\n', /`env` is not a map/], + ['staging', 'host: 192.0.2.1\nsecrets: x\n', /`secrets` is not a map/], + [ + 'staging', + 'host: 192.0.2.1\nenv:\n A: x\nsecrets:\n A: op://a/b/c\n', + /`A` is listed under both `env` and `secrets`/, + ], + ['staging', 'host: 192.0.2.1\nenv:\n PLEXUS_TAG: x\n', /`PLEXUS_TAG` is supplied by the platform; remove it/], + [ + 'staging', + 'host: 192.0.2.1\nsecrets:\n PLEXUS_COMMIT_SHA: op://a/b/c\n', + /`PLEXUS_COMMIT_SHA` is supplied by the platform/, + ], + [ + 'staging', + 'host: 192.0.2.1\nenv:\n COMPOSE_PROJECT_NAME: x\n', + /`COMPOSE_PROJECT_NAME` is supplied by the platform/, + ], + [ + 'staging', + 'host: 192.0.2.1\nenv:\n PLEXUS_LOOPBACK_PORT: x\n', + /`PLEXUS_LOOPBACK_PORT` is supplied by the platform/, + ], ['Staging', 'host: 192.0.2.1\n', /one lowercase word/], ['pre-prod', 'host: 192.0.2.1\n', /one lowercase word/], + ['stage2', 'host: 192.0.2.1\n', /one lowercase word/], ['a.b', 'host: 192.0.2.1\n', /one lowercase word/], ]; for (const [name, text, problem] of cases) { @@ -479,20 +508,58 @@ test('an environment file that cannot be used says why in its own problems, and assert.equal(environment?.name, name, text); assert.equal(environment?.problems.length, 1, `${text}: ${environment?.problems.join('; ')}`); assert.match(environment?.problems[0] ?? '', problem, text); - assert.match(environment?.problems[0] ?? '', new RegExp(`${name.replace('.', '\\.')}\\.yaml`)); + assert.match(environment?.problems[0] ?? '', new RegExp(`^${name.replace('.', '\\.')}\\.yaml: `)); } }); -test('an empty environment file lacks its host and nothing else', async () => { - const [environment] = await environmentsOf({ 'staging.yaml': '' }); - assert.deepEqual(environment?.env, {}); - assert.deepEqual(environment?.secrets, {}); - assert.equal(environment?.host, undefined); - assert.equal(environment?.problems.length, 1); +test('a value under env that is no string is refused, naming the file and the key and saying to quote it, and its name stays listed', async () => { + for (const value of ['3', 'true', '~', '{a: 1}', '[a]', '1.0']) { + const [environment] = await environmentsOf({ 'staging.yaml': `host: 192.0.2.1\nenv:\n KEY: ${value}\n` }); + assert.deepEqual(environment?.problems, ['staging.yaml: `env` `KEY` is not a string; quote it'], value); + assert.deepEqual(environment?.env, {}, value); + assert.deepEqual(environment?.refused, { env: ['KEY'], secrets: [] }, value); + assert.equal(environment?.unread, false); + } }); -test('a secret that is no pointer is still listed under its name, so that only its own problem is reported', async () => { - const [environment] = await environmentsOf({ 'staging.yaml': 'host: 192.0.2.1\nsecrets:\n TOKEN: plain\n' }); - assert.deepEqual(environment?.secrets, { TOKEN: 'plain' }); - assert.equal(environment?.problems.length, 1); +test('a secret that is no pointer is still listed under its name, so that only its own problem is reported; a non-string one is refused but listed', async () => { + const [plain] = await environmentsOf({ 'staging.yaml': 'host: 192.0.2.1\nsecrets:\n TOKEN: plain\n' }); + assert.deepEqual(plain?.secrets, { TOKEN: 'plain' }); + assert.equal(plain?.problems.length, 1); + const [number] = await environmentsOf({ 'staging.yaml': 'host: 192.0.2.1\nsecrets:\n TOKEN: 3\n' }); + assert.deepEqual(number?.secrets, {}); + assert.deepEqual(number?.refused, { env: [], secrets: ['TOKEN'] }); + assert.equal(number?.problems.length, 1); +}); + +test('a file that is empty, not YAML, no map or unreadable is unread, with one problem of its own and no host problem on top', async () => { + const cases: [string | ReturnType, RegExp][] = [ + ['', /^staging\.yaml: is empty; it needs a `host`$/], + ['# nothing\n', /^staging\.yaml: is empty/], + ['host: [\n', /^staging\.yaml: not valid YAML: /], + ['- a\n', /^staging\.yaml: is not a map of `host`/], + ['x', /^staging\.yaml: is not a map of `host`/], + [link('/work/nothing'), /^staging\.yaml: could not be read: ENOENT/], + ]; + for (const [text, problem] of cases) { + const [environment, ...rest] = await environmentsOf({ 'staging.yaml': text }); + assert.equal(rest.length, 0); + assert.equal(environment?.unread, true, String(text)); + assert.equal(environment?.problems.length, 1, `${text}: ${environment?.problems.join('; ')}`); + assert.match(environment?.problems[0] ?? '', problem, String(text)); + } +}); + +test('a `.yml` file in a stack directory is a problem of the stack, naming the file it should be, and no environment', async () => { + const repo = await load({ + stack: { 'compose.yaml': compose(), 'production.yml': 'host: 192.0.2.1\n', 'compose.dev.yml': 'services: {}\n' }, + apps: { shop: dockerfile }, + }); + assert.deepEqual(repo.stacks[0]?.environments, []); + assert.deepEqual(codes(repo), ['bad-environment-file', 'bad-environment-file']); + assert.deepEqual(repo.problems.map((p) => p.message).sort(), [ + 'stack/compose.dev.yml: name it compose.dev.yaml', + 'stack/production.yml: name it production.yaml', + ]); + assert.equal(repo.problems[0]?.stack, 'shop'); }); From bce5fe30432c017d3532ef1a9701cc3af4be3011 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:56:29 +0100 Subject: [PATCH 19/91] Environment files: strings only, one finding per bad value, the platform's names refused, compose file names stated once Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/compose.ts | 6 +- packages/lib/src/doctor.ts | 52 ++++++++----- packages/lib/src/environments.ts | 124 ++++++++++++++++++------------- packages/lib/src/stacks.ts | 33 ++++++-- 4 files changed, 137 insertions(+), 78 deletions(-) diff --git a/packages/lib/src/compose.ts b/packages/lib/src/compose.ts index 6bb0ce6b..a869f8d0 100644 --- a/packages/lib/src/compose.ts +++ b/packages/lib/src/compose.ts @@ -32,6 +32,10 @@ export interface Compose { export const isMapping = (value: unknown): value is Mapping => value !== null && typeof value === 'object' && !Array.isArray(value); +/** What a YAML error says, in one line: `not valid YAML: `. */ +export const yamlError = (error: unknown): string => + `not valid YAML: ${(error as Error).message.split('\n')[0]?.replace(/:$/, '')}`; + /** * A compose file from its text. A file that is not YAML compose could read * (duplicate keys among them) is a usage error naming the file. @@ -41,7 +45,7 @@ export function parseCompose(text: string, path: string): Compose { try { doc = parse(text, { merge: true }); } catch (error) { - throw new UsageError(`${path}: not valid YAML: ${(error as Error).message.split('\n')[0]?.replace(/:$/, '')}`); + throw new UsageError(`${path}: ${yamlError(error)}`); } const declared = isMapping(doc) && isMapping(doc.services) ? doc.services : {}; const written: Record = {}; diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 44db8d66..790de884 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -509,39 +509,53 @@ export const CHECKS: Readonly> /** * What a stack's environment files must meet, none of it a requirement yet - * and so a finding of none, which no deviation silences. A stack without - * environment files meets all of it. Each file is usable (the loader's - * `problems`, one line each); the files list the same names under `env` and - * the same names under `secrets`, one line for each name an environment - * lacks, naming the first that has it; every variable the compose file - * requires by interpolation (`requiredVariables`) is listed under `env` of - * each (compose fills `${…}` from `.env` alone), but for the platform's (`PLATFORM_VARIABLES`); and an - * environment has a `hostname` exactly where the compose file binds - * `PLEXUS_LOOPBACK_PORT`, as the environment gets a port and a route only then. + * and so a finding of none, which no deviation silences, in four groups that + * the requirements will take one to one. A stack without environment files + * meets all of it. (1) The shape: each file is usable, its keys, pointers and + * name, and no `.yml` stands for one (the loader's `problems`, one + * line per bad value). (2) The same names across the files: the files list + * the same names under `env` and under `secrets`, one line for each name an + * environment lacks, naming the first that has it; a file that could not be + * read is left out. (3) Every variable the compose file requires by + * interpolation (`requiredVariables`) is listed under `env` of each (compose + * fills `${…}` from `.env` alone), but for the platform's + * (`PLATFORM_VARIABLES`). (4) An environment has a `hostname` exactly where + * the compose file binds `PLEXUS_LOOPBACK_PORT`, as it gets a port and a route + * only then. */ function environmentFindings(stack: StackFacts): string[] { - const { environments, compose } = stack; - const problems = environments.flatMap((e) => e.problems); + const { compose } = stack; + const environments = stack.environments; + const read = environments.filter((e) => !e.unread); + // The shape of the files, their names and keys and pointers. + const problems = [ + ...stack.problems.filter((p) => p.code === 'bad-environment-file').map((p) => p.message), + ...environments.flatMap((e) => e.problems), + ]; + // The same names across the files. + const listed = (e: Environment, key: 'env' | 'secrets') => [...Object.keys(e[key]), ...e.refused[key]]; for (const key of ['env', 'secrets'] as const) { - const names = [...new Set(environments.flatMap((e) => Object.keys(e[key])))]; + const names = [...new Set(read.flatMap((e) => listed(e, key)))]; for (const name of names) { - const holder = environments.find((e) => name in e[key]); - for (const e of environments) - if (holder && !(name in e[key])) + const holder = read.find((e) => listed(e, key).includes(name)); + for (const e of read) + if (holder && !listed(e, key).includes(name)) problems.push(`${e.name}.yaml lists no \`${name}\` under \`${key}\`, which ${holder.name}.yaml does`); } } - if (compose && environments.length > 0) { + if (compose && read.length > 0) { + // Every required variable listed. for (const variable of requiredVariables(compose).filter((v) => !PLATFORM_VARIABLES.includes(v))) - for (const e of environments) - if (!(variable in e.env)) + for (const e of read) + if (!listed(e, 'env').includes(variable)) problems.push( variable in e.secrets ? `compose.yaml requires \`${variable}\`, which ${e.name}.yaml lists under \`secrets\` only; compose fills \`\${…}\` from \`.env\`, and a secret reaches a container through \`env_file\`, so list it under \`env\`` : `compose.yaml requires \`${variable}\`, which ${e.name}.yaml does not list under \`env\``, ); + // A hostname exactly where the port is bound. const binds = Object.values(compose.services).some((service) => portsOf(service).some(bindsLoopbackVar)); - for (const e of environments) { + for (const e of read) { if (binds && e.hostname === undefined) problems.push( `${e.name}.yaml has no \`hostname\`, but compose.yaml binds \`PLEXUS_LOOPBACK_PORT\`, which needs the public name the proxy serves`, diff --git a/packages/lib/src/environments.ts b/packages/lib/src/environments.ts index 1319c964..57197ffa 100644 --- a/packages/lib/src/environments.ts +++ b/packages/lib/src/environments.ts @@ -1,38 +1,48 @@ // The environments of a stack, and the variables the platform supplies: what // the loader (stacks.ts) reads of a stack's directory beyond its compose file, -// and the one list the checks and the deploy hold a compose file against. +// and the one list `plx doctor` holds environment files and compose files +// against. The stack playbook and the deploy verb will read environment files +// through the loader and take the list from here; nothing outside `lib` reads +// it yet. // // An environment is one stack on one host with its full configuration, and its // configuration is a file in the stack's directory named after it: -// `production.yaml` is the environment `production`. Every `.yaml` of the -// directory is one, but the compose files (`compose.yaml`, `compose.dev.yaml`). -// A name is one lowercase word, letters only, and no name has a meaning: no -// code compares one with a literal. The file is a YAML map with exactly four -// keys: +// `production.yaml` is the environment `production`. The loader (stacks.ts, +// which knows the names of the compose files and has read the directory) +// hands over the file names; a name is one lowercase word, letters only, and +// no name has a meaning: no code compares one with a literal. The file is a +// YAML map with exactly four keys: // host the machine's address, a non-empty string; required // hostname the public name the proxy serves, a non-empty string; optional, // and without it the environment gets no loopback port and no route -// env a map of names to plain values (string, number or boolean, read -// as the string compose would see); absent reads as empty +// env a map of names to strings; absent reads as empty. A value that +// is no string (a number, a boolean, null, a map, a list) is +// refused, not converted: the stack playbook reads the same file +// with another YAML parser, and only a string reads the same in both // secrets a map of names to `op://` pointers, strings; absent reads as empty; // a string that is no pointer is returned and is a problem +// No name stands in both maps, and none is one `PLATFORM_VARIABLES` lists: the +// platform supplies those, so no file does. // `readEnvironments` returns one `Environment` per file in the order of their // names, and never throws: whatever makes a file unusable is a line of its -// `problems` that names the file, and the values it could read are returned -// all the same, so that every problem is found in one run. +// `problems` that names the file, one line per bad value, and the values it +// could read are returned all the same, so that every problem is found in one +// run. A name whose value was refused is in `refused`, so that it still counts +// as listed and its own problem is the only one. A file that could not be +// read at all (unreadable, empty, not YAML, no map) is `unread`: nothing of +// it is known, and it is held to no comparison. // // `requiredVariables` lists the variables a compose file needs its // environment to give: those it interpolates without a default (`${NAME}`, // `$NAME`, `${NAME:?message}`, `${NAME?message}`), not the ones with a // default or an alternative (`${NAME:-x}`, `${NAME-x}`, `${NAME:+x}`, -// `${NAME+x}`); `$$` is compose's escape and no variable. It reads every value of the -// document, as compose does (services, top-level `volumes` and `networks`, -// `x-` fields, lists), and no key. The variables the platform supplies itself -// (`PLATFORM_VARIABLES`) are among them where the file uses them, and are -// listed in no environment file. +// `${NAME+x}`); `$$` is compose's escape and no variable. It reads every +// value of the document, as compose does (services, top-level `volumes` and +// `networks`, `x-` fields, lists), and no key. Compose fills them from `.env`, +// that is from `env`, and never from `.env.secret`. import { join } from 'node:path'; import { parse } from 'yaml'; -import { type Compose, isMapping } from './compose.ts'; +import { type Compose, isMapping, yamlError } from './compose.ts'; import type { Context } from './context.ts'; /** The variables the platform and the deployer supply to a stack, which no environment file lists: the project name and the loopback port in `.env`, the tag and the commit at deploy time. */ @@ -54,62 +64,69 @@ export interface Environment { env: Record; /** Names to `op://` pointers. */ secrets: Record; + /** The names under `env` and under `secrets` whose value was refused: listed, with no value. */ + refused: { env: string[]; secrets: string[] }; + /** The file could not be read as a map at all. */ + unread: boolean; /** What makes the file unusable, one line each, each naming the file. */ problems: string[]; } -/** The files of a stack's directory that hold no environment. */ -const COMPOSE_FILES = new Set(['compose.yaml', 'compose.dev.yaml']); - /** What an environment's name is: one lowercase word. */ const ENVIRONMENT_NAME = /^[a-z]+$/; const KEYS = ['host', 'hostname', 'env', 'secrets']; -/** The environments of the stack whose directory is `dir`, by name. */ -export async function readEnvironments(ctx: Context, dir: string): Promise { - const entries = await ctx.readDir(dir).catch(() => []); - const names = entries - .filter((e) => !e.directory && e.name.endsWith('.yaml') && !COMPOSE_FILES.has(e.name)) - .map((e) => e.name.slice(0, -'.yaml'.length)) - .sort(); +/** The environments in the files `names` (`.yaml`) of the directory `dir`, by name. */ +export async function readEnvironments(ctx: Context, dir: string, names: string[]): Promise { const environments: Environment[] = []; - for (const name of names) environments.push(await readEnvironment(ctx, dir, name)); + for (const file of [...names].sort()) environments.push(await readEnvironment(ctx, dir, file)); return environments; } -async function readEnvironment(ctx: Context, dir: string, name: string): Promise { - const file = join(dir, `${name}.yaml`); - const label = `${name}.yaml`; - const environment: Environment = { name, file, env: {}, secrets: {}, problems: [] }; +async function readEnvironment(ctx: Context, dir: string, label: string): Promise { + const name = label.slice(0, -'.yaml'.length); + const environment: Environment = { + name, + file: join(dir, label), + env: {}, + secrets: {}, + refused: { env: [], secrets: [] }, + unread: false, + problems: [], + }; const problem = (text: string) => environment.problems.push(`${label}: ${text}`); if (!ENVIRONMENT_NAME.test(name)) problem(`\`${name}\` is no environment name; a name is one lowercase word (letters only, no \`-\`)`); - let doc: unknown; + const unread = (text: string): Environment => { + problem(text); + environment.unread = true; + return environment; + }; + let text: string; try { - doc = parse(await ctx.readFile(file)); + text = await ctx.readFile(environment.file); } catch (error) { - problem(`not valid YAML: ${(error as Error).message.split('\n')[0]?.replace(/:$/, '')}`); - return environment; + return unread(`could not be read: ${(error as Error).message}`); } - if (doc === null || doc === undefined) doc = {}; - if (!isMapping(doc)) { - problem('is not a map of `host`, `hostname`, `env` and `secrets`'); - return environment; + let doc: unknown; + try { + doc = parse(text); + } catch (error) { + return unread(yamlError(error)); } + if (doc === null || doc === undefined) return unread('is empty; it needs a `host`'); + if (!isMapping(doc)) return unread('is not a map of `host`, `hostname`, `env` and `secrets`'); for (const key of Object.keys(doc).filter((k) => !KEYS.includes(k))) problem(`unknown key \`${key}\`; the keys are ${KEYS.map((k) => `\`${k}\``).join(', ')}`); + if (doc.host === undefined) problem("has no `host`, the machine's address"); for (const key of ['host', 'hostname'] as const) { const value = doc[key]; if (value === undefined) continue; if (typeof value === 'string' && value !== '') environment[key] = value; else problem(`\`${key}\` is not a non-empty string`); } - if (environment.host === undefined && doc.host === undefined) problem("has no `host`, the machine's address"); - for (const [key, into] of [ - ['env', environment.env], - ['secrets', environment.secrets], - ] as const) { + for (const key of ['env', 'secrets'] as const) { const map = doc[key]; if (map === undefined || map === null) continue; if (!isMapping(map)) { @@ -117,16 +134,19 @@ async function readEnvironment(ctx: Context, dir: string, name: string): Promise continue; } for (const [variable, value] of Object.entries(map)) { - if (key === 'env') { - if (['string', 'number', 'boolean'].includes(typeof value)) into[variable] = String(value); - else problem(`\`env\` \`${variable}\` is not a plain value (a string, a number or a boolean)`); - } else { - if (typeof value === 'string') into[variable] = value; - if (typeof value !== 'string' || !value.startsWith('op://')) - problem(`\`secrets\` \`${variable}\` is no \`op://\` pointer`); - } + if (typeof value === 'string') environment[key][variable] = value; + else environment.refused[key].push(variable); + if (key === 'env' && typeof value !== 'string') problem(`\`env\` \`${variable}\` is not a string; quote it`); + if (key === 'secrets' && !(typeof value === 'string' && value.startsWith('op://'))) + problem(`\`secrets\` \`${variable}\` is no \`op://\` pointer`); } } + const listed = (key: 'env' | 'secrets') => [...Object.keys(environment[key]), ...environment.refused[key]]; + for (const variable of new Set([...listed('env'), ...listed('secrets')])) { + if (listed('env').includes(variable) && listed('secrets').includes(variable)) + problem(`\`${variable}\` is listed under both \`env\` and \`secrets\``); + else if (PLATFORM_VARIABLES.includes(variable)) problem(`\`${variable}\` is supplied by the platform; remove it`); + } return environment; } diff --git a/packages/lib/src/stacks.ts b/packages/lib/src/stacks.ts index bda66a4f..37acf050 100644 --- a/packages/lib/src/stacks.ts +++ b/packages/lib/src/stacks.ts @@ -46,6 +46,8 @@ // (lowercase letters, digits, `-` and `_`, starting // with a letter or digit) // bad-compose a `compose.yaml` that is not YAML compose can read +// bad-environment-file a `.yml` in a stack's directory, which is no +// environment file; the problem says to name it `.yaml` // unused-app an app that no stack uses // unknown-app a service whose image carries the tag variable and // names no app, or whose pinned image is in a registry @@ -60,6 +62,10 @@ import { MARKER_FILE, splitFrontmatter } from './marker.ts'; import { APPS_DIR } from './model.ts'; import { isDirectory } from './overview.ts'; +/** The names of a stack's compose files: the one the deploy reads, and the one a developer runs locally. */ +export const COMPOSE_FILE = 'compose.yaml'; +export const DEV_COMPOSE_FILE = 'compose.dev.yaml'; + /** The key of the root marker that names the repo; a key of the marker's own, no question of a template. */ export const REPO_KEY = 'repo'; @@ -120,6 +126,7 @@ export type StackProblemCode = | 'no-compose' | 'bad-name' | 'bad-compose' + | 'bad-environment-file' | 'unused-app' | 'unknown-app'; @@ -151,8 +158,9 @@ export async function loadStacks(ctx: Context, rootGiven: string): Promise { - const entries = new Set((await ctx.readDir(dir)).map((e) => e.name)); + const listing = await ctx.readDir(dir); + const entries = new Set(listing.map((e) => e.name)); + const files = listing.filter((e) => !e.directory).map((e) => e.name); + for (const file of files.filter((f) => f.endsWith('.yml'))) + problems.push({ + code: 'bad-environment-file', + message: `${join(where, file)}: name it ${file.slice(0, -'.yml'.length)}.yaml`, + stack: name, + }); const marker = entries.has(MARKER_FILE) ? await readMarker(ctx, join(dir, MARKER_FILE)) : undefined; - const file = join(dir, 'compose.yaml'); + const file = join(dir, COMPOSE_FILE); const used: Pick = { apps: [], pinned: [] }; let images: Image[] = []; const text = await ctx.readFile(file).catch(() => undefined); @@ -229,10 +246,14 @@ async function stackAt( name, dir, compose: file, - dev: entries.has('compose.dev.yaml'), + dev: entries.has(DEV_COMPOSE_FILE), ...(marker === undefined ? {} : { marker }), ...used, - environments: await readEnvironments(ctx, dir), + environments: await readEnvironments( + ctx, + dir, + files.filter((f) => f.endsWith('.yaml') && f !== COMPOSE_FILE && f !== DEV_COMPOSE_FILE), + ), }; return { stack, images, hasCompose: text !== undefined }; } From 87fa7a754848030355d63d96777960ec27ffb797 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:56:39 +0100 Subject: [PATCH 20/91] The old routes stay imported until apps.caddy is deleted, without a platform run Caddy refuses a missing import path but imports nothing for a pattern that matches no file, so the root imports /etc/caddy/apps*.caddy where apps.caddy was there when the root was written. The role's header names what the stack playbook uses (the fragment directory and form, the snippet stack, the reload rule and how a reload fails) and how old routes and fragments coexist while a host migrates. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/roles/ingress/tasks/main.yml | 39 ++++++++++++++++--- .../roles/ingress/templates/root.Caddyfile.j2 | 7 +++- 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/ansible/platform/roles/ingress/tasks/main.yml b/ansible/platform/roles/ingress/tasks/main.yml index 5ab896eb..3cc4f787 100644 --- a/ansible/platform/roles/ingress/tasks/main.yml +++ b/ansible/platform/roles/ingress/tasks/main.yml @@ -1,12 +1,41 @@ --- # Counterpart of caddy (PLX-Ingress): caddy installs and enables the server; # this role owns its configuration and runs after it in the platform playbook, -# since validating the configuration needs the binary. +# since validating the configuration needs the binary. It knows no stack: it +# writes the root Caddyfile and prepares what the stack playbook writes routes +# with, and writes no route itself. # -# The routes of earlier versions: they rendered every route of the host from -# plexus_apps into /etc/caddy/apps.caddy. This role no longer writes that file -# and never removes it: the root configuration imports it for as long as it is -# there. +# What the stack playbook uses, by these names: +# - The directory of route fragments, ingress_fragments_dir +# (/etc/caddy/stacks), owned by the deploy user. One file per environment +# that has a hostname, -.caddy, and exactly +# { +# import stack +# } +# The root Caddyfile imports every *.caddy there and defines the snippet +# `stack`: the proxy to 127.0.0.1:, the refusal of /healthz and the +# maintenance page, the same for every stack. +# - The reload rule, /etc/sudoers.d/reload-caddy, exactly +# ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy +# run as `sudo -n /usr/bin/systemctl reload caddy`. The reload reads the +# whole configuration again; where it is invalid (a fragment that does not +# parse, a hostname that two files serve), the reload fails, the proxy goes +# on serving what it served, and every later reload, of any stack's, and +# this role's validation fail too until the file is mended or removed. The +# deploy user can run `caddy validate --config /etc/caddy/Caddyfile` first. +# +# While a host migrates, the routes of earlier versions and the fragments +# coexist. Earlier versions rendered every route of the host from plexus_apps +# into /etc/caddy/apps.caddy; this role no longer writes that file and never +# removes it, and the root Caddyfile imports it, where it was there when the +# root was written, beside the fragments. The proxy refuses a hostname that +# both serve, so a person takes an environment's hostname out of apps.caddy +# before the environment's first deploy that writes its fragment: the old +# route goes on being served until that deploy's reload moves the hostname to +# the fragment. A fragment serves a hostname whole: a hostname apps.caddy +# splits by path prefix among several deployments moves to one environment, +# or each deployment takes a hostname of its own. Once apps.caddy holds no +# route, the person deletes it; the next run of this role drops its import. - name: Look for the routes of earlier versions ansible.builtin.stat: diff --git a/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 b/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 index c096a0c3..0f332d6c 100644 --- a/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 +++ b/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 @@ -62,8 +62,11 @@ {% if ingress_earlier_routes.stat.exists %} # The routes earlier versions rendered from the inventory's records, left as -# they were until removed by hand. -import /etc/caddy/apps.caddy +# they were until removed by hand. A pattern, not the path: Caddy imports +# nothing for a pattern that matches no file but refuses a missing path, so +# apps.caddy can be deleted without a run of the platform playbook. Keep no +# other file here whose name begins with apps and ends in .caddy. +import /etc/caddy/apps*.caddy {% endif %} # The stacks' routes, one fragment per environment, written by the stack playbook. From efca3604efb92e330ab8d1b0bf21b8426893f34d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:56:56 +0100 Subject: [PATCH 21/91] Test: SinglePort lets a stack with environment files and no hostname bind no port Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.test.ts | 44 +++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 86c05f69..3199c252 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -2558,3 +2558,47 @@ test('an environment that could not be read is left out of the comparisons with const found = await environmentFindings(environmentFiles({ 'staging.yaml': '' })); assert.equal(found.length, 1, found.join('\n')); }); + +/** The stack's findings over a compose file and environment files. */ +async function stackFindings(files: Tree) { + const { of } = await webReport((web) => withStack(web, files)); + return of('stack'); +} +const NO_PORT = FROM_ENV.replace(/ {4}ports: .*\n/, ''); +const NO_HOSTNAME = (text: string) => text.replace(/hostname: .*\n/, ''); + +test('PLX-Stack/SinglePort: with environment files that all lack a hostname a stack binds no port and passes, once', async () => { + const found = await stackFindings( + environmentFiles({ + 'compose.yaml': compose(NO_PORT), + 'production.yaml': NO_HOSTNAME(PRODUCTION), + 'staging.yaml': NO_HOSTNAME(STAGING), + }), + ); + assert.deepEqual(found, []); +}); + +test('PLX-Stack/SinglePort: without environment files a stack still binds exactly one port', async () => { + const found = await stackFindings({ 'compose.yaml': compose(NO_PORT) }); + assert.deepEqual( + found.map((f) => [f.requirement, f.problem]), + [['PLX-Stack/SinglePort', 'no service binds `PLEXUS_LOOPBACK_PORT`: the stack serves no port']], + ); +}); + +test('a stack whose environments have hostnames and whose compose file binds no port is reported once, by the hostname', async () => { + const found = await stackFindings(environmentFiles({ 'compose.yaml': compose(NO_PORT) })); + assert.deepEqual( + found.map((f) => f.requirement), + [undefined, undefined], + ); + assert.ok(found.every((f) => /has a `hostname`, but compose.yaml binds no/.test(f.problem))); +}); + +test('PLX-Stack/SinglePort: with environment files a stack that binds two port mappings fails once, by SinglePort', async () => { + const twice = FROM_ENV.replace(/( {4}ports: )(.*)\n/, '$1[$2, "127.0.0.1:${PLEXUS_LOOPBACK_PORT:?set}:3001"]\n'); + const found = await stackFindings(environmentFiles({ 'compose.yaml': compose(twice) })); + const single = found.filter((f) => f.requirement === 'PLX-Stack/SinglePort'); + assert.equal(single.length, 1, found.map((f) => f.problem).join('\n')); + assert.equal(found.filter((f) => f.requirement === undefined).length, 0); +}); From 0954da3da751138739b9dd926599d232092daf64 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:57:09 +0100 Subject: [PATCH 22/91] The platform playbook's header says it writes no route Co-Authored-By: Claude Opus 5.5 --- ansible/platform/playbooks/playbook.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ansible/platform/playbooks/playbook.yml b/ansible/platform/playbooks/playbook.yml index 553846a5..bf3590ac 100644 --- a/ansible/platform/playbooks/playbook.yml +++ b/ansible/platform/playbooks/playbook.yml @@ -13,10 +13,10 @@ # host (the deploy user, the deploy root, the proxy with its directory of route # fragments, and the one rule by which the deploy user reloads the proxy), and # the stack playbook (plexus.platform.stack) does everything one environment -# needs. It starts, re-creates and removes no container, and changes nothing -# below the deploy root but the root's own owner. `plexus_apps`, the records of -# earlier versions, is not read; a host that still sets it is told so, and the -# run goes on. +# needs. It starts, re-creates and removes no container, changes nothing below +# the deploy root, and writes no route. `plexus_apps`, the records of earlier +# versions, is not read; a host that still sets records in it is told so, and +# the run goes on. # # A fresh host is reached as root once (`-u root`), which creates the admins; # every later run connects as an admin, and the first of those closes root From 8fb808a82eaa033548068e4c24e0478c3e0f9b28 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:57:18 +0100 Subject: [PATCH 23/91] SinglePort: a stack with environment files binds a port only where a hostname needs one Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.ts | 11 +++++++++-- packages/lib/src/testing/doctor-checks.md | 2 +- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 790de884..76c32016 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -370,12 +370,19 @@ function noCommittedValues(repo: RepoFacts): string[] { .map((f) => `the source repo tracks \`${f}\``); } -function singlePort(compose: Compose): string[] { +/** + * Exactly one service binds the loopback variable, in one port mapping. A + * stack with environment files may bind none: whether it must is the + * environments' `hostname` (`environmentFindings`), which reports a hostname + * without a port, so that no case is reported twice. + */ +function singlePort(compose: Compose, stack: StackFacts): string[] { const binders = Object.entries(compose.services) .map(([name, service]) => [name, portsOf(service).filter(bindsLoopbackVar).length] as const) .filter(([, bound]) => bound > 0); const mappings = binders.reduce((sum, [, bound]) => sum + bound, 0); - if (binders.length === 0) return ['no service binds `PLEXUS_LOOPBACK_PORT`: the stack serves no port']; + if (binders.length === 0) + return stack.environments.length > 0 ? [] : ['no service binds `PLEXUS_LOOPBACK_PORT`: the stack serves no port']; if (mappings === 1) return []; const names = binders.map(([name]) => `\`${name}\``).join(', '); const who = binders.length === 1 ? `the service ${names} binds` : `the services ${names} bind`; diff --git a/packages/lib/src/testing/doctor-checks.md b/packages/lib/src/testing/doctor-checks.md index 267b89c4..dfe63269 100644 --- a/packages/lib/src/testing/doctor-checks.md +++ b/packages/lib/src/testing/doctor-checks.md @@ -22,7 +22,7 @@ set to a compendium checkout it reads the pages themselves instead. `plx doctor` checks `PLX-Stack/EnvFileLoad` on the service that publishes the loopback port and on every service that runs the image of one of the stack's apps, and of `PLX-Stack/NoCommittedValues` that the repo tracks no `.env` and no `.env.secret`. -`plx doctor` checks of `PLX-Stack/SinglePort` that exactly one service binds `PLEXUS_LOOPBACK_PORT`, in exactly one port mapping, not that it speaks plain HTTP, and checks `PLX-Stack/LoopbackPort`. +`plx doctor` checks of `PLX-Stack/SinglePort` that exactly one service binds `PLEXUS_LOOPBACK_PORT`, in exactly one port mapping (none, where the stack has environment files, whose `hostname` decides whether the port is bound), not that it speaks plain HTTP, and checks `PLX-Stack/LoopbackPort`. `plx doctor` checks of `PLX-Stack/Healthcheck` that each of those services declares a `healthcheck` with a test of its own that is not disabled. From fa6507981af84796019a1884a4626cbaa58e7aee Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:58:29 +0100 Subject: [PATCH 24/91] Test: host is an SSH destination parsed once; platform and doubled names are not also reported missing Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.test.ts | 19 +++++++++++ packages/lib/src/stacks.test.ts | 58 +++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 3199c252..34966c05 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -2602,3 +2602,22 @@ test('PLX-Stack/SinglePort: with environment files a stack that binds two port m assert.equal(single.length, 1, found.map((f) => f.problem).join('\n')); assert.equal(found.filter((f) => f.requirement === undefined).length, 0); }); + +test('a name the platform supplies, or listed under both maps, is not also reported as missing from the other files', async () => { + const platform = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace('env:\n', 'env:\n PLEXUS_TAG: x\n') }), + ); + assert.deepEqual(platform, ['staging.yaml: `PLEXUS_TAG` is supplied by the platform; remove it']); + const both = await environmentFindings( + environmentFiles({ 'staging.yaml': `${STAGING} MODE: op://acme/shop/mode\n` }), + ); + assert.deepEqual(both, ['staging.yaml: `MODE` is listed under both `env` and `secrets`']); +}); + +test('a malformed host is one finding of the file', async () => { + const found = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace('192.0.2.2', 'ssh://192.0.2.2') }), + ); + assert.equal(found.length, 1); + assert.match(found[0] ?? '', /^staging\.yaml: `host` is not `\[user@\]address\[:port\]`/); +}); diff --git a/packages/lib/src/stacks.test.ts b/packages/lib/src/stacks.test.ts index bece0846..f1963e07 100644 --- a/packages/lib/src/stacks.test.ts +++ b/packages/lib/src/stacks.test.ts @@ -421,6 +421,7 @@ test("a stack's environments are its `.yaml` files but the compose files, name: 'production', file: '/work/shop/stack/production.yaml', host: '192.0.2.1', + target: { address: '192.0.2.1' }, hostname: 'shop.example.com', env: { MODE: 'production' }, secrets: { TOKEN: 'op://acme/shop/token' }, @@ -432,6 +433,7 @@ test("a stack's environments are its `.yaml` files but the compose files, name: 'staging', file: '/work/shop/stack/staging.yaml', host: '192.0.2.2', + target: { address: '192.0.2.2' }, env: { MODE: 'staging', RETRIES: '3', DEBUG: 'true' }, secrets: {}, refused: { env: [], secrets: [] }, @@ -563,3 +565,59 @@ test('a `.yml` file in a stack directory is a problem of the stack, naming ]); assert.equal(repo.problems[0]?.stack, 'shop'); }); + +test('`host` is an SSH destination, `[user@]address[:port]`, returned as written and parsed, absence being absence', async () => { + const cases: [string, Record][] = [ + ['192.0.2.1', { address: '192.0.2.1' }], + ['shop.example.com', { address: 'shop.example.com' }], + ['192.0.2.1:22', { address: '192.0.2.1', port: 22 }], + ['deploy@192.0.2.10:2222', { address: '192.0.2.10', user: 'deploy', port: 2222 }], + ['deploy@shop.example.com', { address: 'shop.example.com', user: 'deploy' }], + ['2001:db8::1', { address: '2001:db8::1' }], + ['deploy@2001:db8::1', { address: '2001:db8::1', user: 'deploy' }], + ['[2001:db8::1]', { address: '2001:db8::1' }], + ['[2001:db8::1]:2222', { address: '2001:db8::1', port: 2222 }], + ['deploy@[2001:db8::1]:65535', { address: '2001:db8::1', user: 'deploy', port: 65535 }], + ['192.0.2.1:1', { address: '192.0.2.1', port: 1 }], + ]; + for (const [host, target] of cases) { + const [environment] = await environmentsOf({ 'staging.yaml': `host: "${host}"\n` }); + assert.deepEqual(environment?.problems, [], host); + assert.equal(environment?.host, host); + assert.deepEqual(environment?.target, target, host); + } +}); + +test('a `host` that is no SSH destination is one problem naming the file and showing the form, and no host', async () => { + const bad = [ + '@192.0.2.1', + 'deploy@', + '192.0.2.1:', + ':22', + '192.0.2.1:0', + '192.0.2.1:65536', + '192.0.2.1:ab', + '192.0.2.1:-1', + '192.0.2.1 ', + '192.0.2.1 x', + 'ssh://192.0.2.1', + '192.0.2.1/path', + 'a@b@c', + '[2001:db8::1', + '[2001:db8::1]x', + '[2001:db8::1]:', + '[]', + 'de ploy@192.0.2.1', + ]; + for (const host of bad) { + const [environment] = await environmentsOf({ 'staging.yaml': `host: "${host}"\n` }); + assert.equal(environment?.problems.length, 1, host); + assert.match( + environment?.problems[0] ?? '', + /^staging\.yaml: `host` is not `\[user@\]address\[:port\]`.*deploy@192\.0\.2\.10:2222/, + host, + ); + assert.equal(environment?.host, undefined, host); + assert.equal(environment?.target, undefined, host); + } +}); From e97916ea66603abeea13dff8ce1790a9ae7e7252 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:59:00 +0100 Subject: [PATCH 25/91] host is an SSH destination, parsed once by the loader; doubled and platform names are reported once Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.ts | 7 +++- packages/lib/src/environments.ts | 71 +++++++++++++++++++++++++++++--- packages/lib/src/index.ts | 2 + 3 files changed, 73 insertions(+), 7 deletions(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 76c32016..88ab99ab 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -541,8 +541,13 @@ function environmentFindings(stack: StackFacts): string[] { ]; // The same names across the files. const listed = (e: Environment, key: 'env' | 'secrets') => [...Object.keys(e[key]), ...e.refused[key]]; + // A name the platform supplies or one listed under both maps has its finding already. + const doubled = new Set([ + ...PLATFORM_VARIABLES, + ...read.flatMap((e) => listed(e, 'env').filter((n) => listed(e, 'secrets').includes(n))), + ]); for (const key of ['env', 'secrets'] as const) { - const names = [...new Set(read.flatMap((e) => listed(e, key)))]; + const names = [...new Set(read.flatMap((e) => listed(e, key)))].filter((n) => !doubled.has(n)); for (const name of names) { const holder = read.find((e) => listed(e, key).includes(name)); for (const e of read) diff --git a/packages/lib/src/environments.ts b/packages/lib/src/environments.ts index 57197ffa..501389fe 100644 --- a/packages/lib/src/environments.ts +++ b/packages/lib/src/environments.ts @@ -12,7 +12,13 @@ // hands over the file names; a name is one lowercase word, letters only, and // no name has a meaning: no code compares one with a literal. The file is a // YAML map with exactly four keys: -// host the machine's address, a non-empty string; required +// host the machine as an SSH destination, `[user@]address[:port]`, as in +// `deploy@192.0.2.10:2222`; required. The address is a name or an +// IPv4 or IPv6 address, the last in brackets where a port follows +// and bare otherwise. It is returned as written (`host`) and +// parsed (`target`: the address, the user and the port where given, +// absent where not; the default user and port are the connecting +// side's to name, not this file's) // hostname the public name the proxy serves, a non-empty string; optional, // and without it the environment gets no loopback port and no route // env a map of names to strings; absent reads as empty. A value that @@ -53,13 +59,59 @@ export const PLATFORM_VARIABLES: readonly string[] = [ 'PLEXUS_COMMIT_SHA', ]; +/** An SSH destination, parsed. */ +export interface SshTarget { + address: string; + user?: string; + port?: number; +} + +/** The form of `host`, shown in the finding. */ +const HOST_FORM = '`[user@]address[:port]`, as in `deploy@192.0.2.10:2222`'; + +/** A `host` parsed, or why it is no SSH destination. */ +export function parseHost(host: string): SshTarget | string { + if (/\s/.test(host)) return 'it holds whitespace'; + if (host.includes('/')) return 'it holds a scheme or a path'; + const at = host.lastIndexOf('@'); + const user = at < 0 ? undefined : host.slice(0, at); + const rest = host.slice(at + 1); + if (user !== undefined && (user === '' || /[@:]/.test(user))) return 'the user is empty or holds `@` or `:`'; + let address = rest; + let port: string | undefined; + if (rest.startsWith('[')) { + const close = rest.indexOf(']'); + if (close < 0) return 'a bracket is not closed'; + address = rest.slice(1, close); + const after = rest.slice(close + 1); + if (after !== '') { + if (!after.startsWith(':')) return 'only a port may follow the closing bracket'; + port = after.slice(1); + } + if (!/^[0-9a-fA-F:.]*:[0-9a-fA-F:.]*$/.test(address)) return 'the bracketed address is no IPv6 address'; + } else if (rest.split(':').length > 2) { + if (!/^[0-9a-fA-F:.]+$/.test(rest)) return 'the address is no IPv6 address'; + } else if (rest.includes(':')) { + [address = '', port] = rest.split(':'); + } + if (address === '') return 'the address is empty'; + if (!rest.startsWith('[') && !address.includes(':') && !/^[A-Za-z0-9._-]+$/.test(address)) + return 'the address holds characters no name or address has'; + if (port !== undefined && !(/^[0-9]{1,5}$/.test(port) && Number(port) >= 1 && Number(port) <= 65535)) + return 'the port is not a number from 1 to 65535'; + return { address, ...(user === undefined ? {} : { user }), ...(port === undefined ? {} : { port: Number(port) }) }; +} + /** One stack on one host, as its file states it. */ export interface Environment { /** The file's name without `.yaml`. */ name: string; /** The file, absolute. */ file: string; + /** The `host` as written; absent where there is none or it is malformed. */ host?: string; + /** The `host` parsed: the user and the port only where it gives them. */ + target?: SshTarget; hostname?: string; env: Record; /** Names to `op://` pointers. */ @@ -120,11 +172,18 @@ async function readEnvironment(ctx: Context, dir: string, label: string): Promis for (const key of Object.keys(doc).filter((k) => !KEYS.includes(k))) problem(`unknown key \`${key}\`; the keys are ${KEYS.map((k) => `\`${k}\``).join(', ')}`); if (doc.host === undefined) problem("has no `host`, the machine's address"); - for (const key of ['host', 'hostname'] as const) { - const value = doc[key]; - if (value === undefined) continue; - if (typeof value === 'string' && value !== '') environment[key] = value; - else problem(`\`${key}\` is not a non-empty string`); + if (doc.host !== undefined) { + const target = typeof doc.host === 'string' && doc.host !== '' ? parseHost(doc.host) : undefined; + if (target === undefined) problem('`host` is not a non-empty string'); + else if (typeof target === 'string') problem(`\`host\` is not ${HOST_FORM}: ${target}`); + else { + environment.host = doc.host as string; + environment.target = target; + } + } + if (doc.hostname !== undefined) { + if (typeof doc.hostname === 'string' && doc.hostname !== '') environment.hostname = doc.hostname; + else problem('`hostname` is not a non-empty string'); } for (const key of ['env', 'secrets'] as const) { const map = doc[key]; diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index ffb3ff36..5f227c45 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -80,8 +80,10 @@ export { envFlag } from './envFlag.ts'; export { type Environment, PLATFORM_VARIABLES, + parseHost, readEnvironments, requiredVariables, + type SshTarget, } from './environments.ts'; export { frontmatterField, setFrontmatterField } from './frontmatter.ts'; export { From d2f65b3698b56b4acdfa15d3340671e028897f5e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:59:37 +0100 Subject: [PATCH 26/91] Drop two guards of the host parser that others make redundant Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/environments.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/lib/src/environments.ts b/packages/lib/src/environments.ts index 501389fe..2e1e8fe1 100644 --- a/packages/lib/src/environments.ts +++ b/packages/lib/src/environments.ts @@ -94,10 +94,9 @@ export function parseHost(host: string): SshTarget | string { } else if (rest.includes(':')) { [address = '', port] = rest.split(':'); } - if (address === '') return 'the address is empty'; if (!rest.startsWith('[') && !address.includes(':') && !/^[A-Za-z0-9._-]+$/.test(address)) - return 'the address holds characters no name or address has'; - if (port !== undefined && !(/^[0-9]{1,5}$/.test(port) && Number(port) >= 1 && Number(port) <= 65535)) + return 'the address is empty or holds characters no name or address has'; + if (port !== undefined && !(/^[0-9]+$/.test(port) && Number(port) >= 1 && Number(port) <= 65535)) return 'the port is not a number from 1 to 65535'; return { address, ...(user === undefined ? {} : { user }), ...(port === undefined ? {} : { port: Number(port) }) }; } From ed08b51837c453b1c2aaf30a3f4fea0379e662c1 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 01:59:52 +0100 Subject: [PATCH 27/91] Test: a version lands on the default branch of origin, whatever the repo is Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/consumers.test.ts | 95 +++++++++++++++++++++++------- 1 file changed, 75 insertions(+), 20 deletions(-) diff --git a/packages/lib/src/consumers.test.ts b/packages/lib/src/consumers.test.ts index 2d2d2694..1f066c8c 100644 --- a/packages/lib/src/consumers.test.ts +++ b/packages/lib/src/consumers.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { expectedBranch, findRepos } from './consumers.ts'; +import { findRepos } from './consumers.ts'; import { Context } from './context.ts'; import type { Directory } from './model.ts'; import { fakeIo } from './testing/fakeIo.ts'; @@ -13,25 +13,6 @@ const dir = (path: string, facets: Partial = {}, children: Directory[ }); const marker = () => ({ declaration: { deviations: [], body: '' } }); -test('expectedBranch follows what the markers say the repo is, and the answers for a package repo', () => { - const config = (templates: string[], answers: Record = {}) => ({ - config: { version: '0.2.0', templates, deviations: [], answers }, - }); - assert.equal(expectedBranch(dir('/o', { ...config(['repo-operations']), ...marker() })), 'main'); - assert.equal(expectedBranch(dir('/w', { ...config(['repo-turbo']), ...marker() })), 'develop'); - assert.equal( - expectedBranch(dir('/l', { ...config(['repo-turbo'], { publishes_packages: true }), ...marker() })), - 'main', - 'a package repo, by the answer in its marker', - ); - assert.equal(expectedBranch(dir('/x', config(['repo-operations']))), undefined, 'no marker'); - assert.equal( - expectedBranch(dir('/y', { ...marker(), uncrossed: true })), - undefined, - 'not crossed over: the checkout’s', - ); -}); - test('findRepos takes a repo by a root marker that names a version or lists templates, or by an answers file beside its marker', async () => { const git = { branch: 'develop', dirty: false }; const config = (keys: Record) => ({ config: { deviations: [], answers: {}, ...keys } }); @@ -53,3 +34,77 @@ test('findRepos takes a repo by a root marker that names a version or lists temp 'a repo with templates and no version is found, for update to refuse it by name, and one that has not crossed over, for update to refuse it with the runbook', ); }); + +/** A workspace of one marked repo `name` per kind, with what `git` answers about its origin's default branch. */ +const kinds: Record = { + shop: ['repo-turbo'], + platform: ['repo-operations'], +}; +async function consumersWith( + git: (args: string[]) => string | undefined, + facets: Partial = {}, + names = Object.keys(kinds), +) { + const repos = names.map((name) => + dir(`/w/${name}`, { + git: { branch: 'checked-out', dirty: false }, + ...marker(), + config: { version: '0.2.0', templates: kinds[name] ?? [], deviations: [], answers: {} }, + ...facets, + }), + ); + const ctx = new Context( + { quiet: true }, + fakeIo({}, (_cwd, args) => (args[0] === 'remote' ? 'git@example.com:acme/x.git' : git(args))), + ); + return findRepos(ctx, dir('/w', {}, repos)); +} + +test('a version lands on the default branch of origin that the checkout records, in an app repo and an operations repo alike, with no call to origin', async () => { + const calls: string[][] = []; + const repos = await consumersWith((args) => { + calls.push(args); + return args[0] === 'symbolic-ref' ? 'origin/trunk' : undefined; + }); + assert.deepEqual( + repos.map((r) => [r.rel, r.branch, r.skipped]), + [ + ['shop', 'trunk', undefined], + ['platform', 'trunk', undefined], + ], + ); + assert.ok(!calls.some((c) => c[0] === 'ls-remote')); +}); + +test('a checkout that records no default branch asks origin for its HEAD', async () => { + const repos = await consumersWith((args) => + args[0] === 'ls-remote' ? 'ref: refs/heads/develop\tHEAD\n0123456789abcdef\tHEAD\n' : undefined, + ); + assert.deepEqual( + repos.map((r) => [r.branch, r.skipped]), + [ + ['develop', undefined], + ['develop', undefined], + ], + ); +}); + +test('a repo whose default branch cannot be determined is skipped with why and what to do, never guessed', async () => { + const repos = await consumersWith(() => undefined, {}, ['shop']); + assert.equal(repos[0]?.branch, 'checked-out', 'the branch it is on is no answer'); + assert.match(repos[0]?.skipped ?? '', /default branch of origin cannot be determined/); + assert.match(repos[0]?.skipped ?? '', /git remote set-head origin -a/); + const odd = await consumersWith((args) => (args[0] === 'ls-remote' ? 'no symref here\n' : undefined), {}, ['shop']); + assert.match(odd[0]?.skipped ?? '', /cannot be determined/); +}); + +test('a repo that has not crossed over is taken on the branch its checkout is on, and origin is not asked', async () => { + const repos = await consumersWith( + () => { + throw new Error('asked'); + }, + { uncrossed: true, config: undefined }, + ['shop'], + ); + assert.deepEqual([repos[0]?.branch, repos[0]?.skipped], ['checked-out', undefined]); +}); From f78e562758ed3876d8780295d424a22997d80812 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:01:47 +0100 Subject: [PATCH 28/91] Test: the integration fixtures give each origin a default branch, and update lands on it Co-Authored-By: Claude Sonnet 5.5 --- packages/dev/src/ship.integration.test.ts | 44 +++++++++++++++++++++-- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index c62b4bbb..906d8b56 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -371,9 +371,10 @@ const fakeLog = () => read(FAKE_LOG()).split('\n').filter(Boolean); const up = (r: string) => join(WS, 'plexus-ms', r); const remote = (r: string) => join(WS, 'remotes', `${r}.git`); -/** A bare origin for a repo, with its branches and tags pushed. */ +/** A bare origin for a repo, with its branches and tags pushed, and the branch the repo is on as its default. */ const withOrigin = (path: string, name: string) => { git(WS, 'init', '--quiet', '--bare', remote(name)); + git(remote(name), 'symbolic-ref', 'HEAD', `refs/heads/${git(path, 'symbolic-ref', '--short', 'HEAD')}`); git(path, 'remote', 'add', 'origin', remote(name)); git(path, 'push', '--quiet', 'origin', '--all'); git(path, 'push', '--quiet', 'origin', '--tags'); @@ -1480,12 +1481,49 @@ test('update --recursive: a named version is validated, and asks every repo for assert.equal(result?.pulls.length, 2); }); -test('update --recursive: a repo whose origin lacks the branch the version lands on is skipped, with the reason', async () => { +test('update --recursive: an app repo whose default branch is main, with no develop, takes the version on main', async () => { + fixture('default-main'); + git(remote('acme-web'), 'branch', '--quiet', '-m', 'develop', 'main'); + git(remote('acme-web'), 'symbolic-ref', 'HEAD', 'refs/heads/main'); + const { result, error, out } = await runRecursive({ yes: true }, { to: '0.2.0' }); + assert.equal(error, undefined, out); + assert.deepEqual(result?.skipped, []); + assert.equal(pull('acme-web', '0.2.0', '.base'), 'main'); + assert.equal(git(remote('acme-web'), 'rev-list', '--count', 'main..plexus/0.2.0'), '1'); + const alone = await runUpdate({ yes: true }, { repo: join(WS, 'acme/platform'), to: '0.2.0' }); + assert.equal(alone.error, undefined, alone.out); + assert.equal(pull('acme-platform', '0.2.0', '.base'), 'main'); +}); + +test('update: an operations repo takes the version on its default branch, whatever it is called', async () => { + fixture('default-trunk'); + git(remote('acme-platform'), 'branch', '--quiet', '-m', 'main', 'trunk'); + git(remote('acme-platform'), 'symbolic-ref', 'HEAD', 'refs/heads/trunk'); + const { result, error, out } = await runUpdate({ yes: true }, { repo: join(WS, 'acme/platform'), to: '0.2.0' }); + assert.equal(error, undefined, out); + assert.deepEqual(result?.skipped, []); + assert.equal(pull('acme-platform', '0.2.0', '.base'), 'trunk'); +}); + +test('update --recursive: a repo whose origin says no default branch is skipped, with why and what to do', async () => { + fixture('no-default'); + git(remote('acme-web'), 'update-ref', '-d', 'refs/heads/develop'); + const { result, error, out } = await runRecursive({ yes: true }, { to: '0.2.0' }); + assert.equal(error, undefined, out); + assert.match(out, /⚠ acme\/web: the default branch of origin cannot be determined.*set-head origin -a.* — skipped/); + assert.equal(result?.skipped.length, 1); + assert.deepEqual(result?.failed, []); + assert.equal(result?.pulls.length, 1, 'the other repo takes the version'); +}); + +test('update --recursive: a repo whose checkout records a default branch that origin lost is skipped, with the reason', async () => { fixture('no-branch'); + git(join(WS, 'acme/web'), 'remote', 'set-head', 'origin', 'develop'); git(remote('acme-web'), 'update-ref', '-d', 'refs/heads/develop'); const { result, error, out } = await runRecursive({ yes: true }, { to: '0.2.0' }); assert.equal(error, undefined, out); - const reason = 'origin has no branch `develop`, the one the version lands on'; + const reason = + 'origin has no branch `develop`, the default branch the version lands on; if the default branch changed on the forge, `git remote set-head origin -a` refreshes what the checkout records'; assert.ok(has(out, `⚠ acme/web: ${reason} — skipped`), out); assert.deepEqual(result?.skipped, [{ path: 'acme/web', reason }]); assert.deepEqual(result?.failed, []); From 4e6f7b8df35551571fbf01deba92f3d7f3a195ee Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:04:47 +0100 Subject: [PATCH 29/91] plx update lands a version on the default branch of origin A repo's kind no longer decides the branch: it is read from origin/HEAD of the checkout, else from origin's own HEAD, and a repo with neither is skipped. Co-Authored-By: Claude Sonnet 5.5 --- packages/dev/src/ship.integration.test.ts | 14 ++-- packages/lib/src/consumers.ts | 78 +++++++++++++++-------- packages/lib/src/index.ts | 2 +- packages/lib/src/update.ts | 6 +- 4 files changed, 64 insertions(+), 36 deletions(-) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index 906d8b56..711c25c3 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -2736,7 +2736,7 @@ test('update: the dry run says a conflict would be committed with its markers, n assert.ok(!has(out, 'CONFLICTS at web/apps/site, committed'), 'nothing is committed in a dry run'); }); -test('the preview reports a consumer without an origin, one that cannot be cloned and one that has not crossed over, and removes its scratch', async () => { +test('the preview reports a consumer without an origin, one whose origin cannot be asked and one that has not crossed over, and removes its scratch', async () => { fixture('dry-others'); const tmp = join(WS, 'tmp'); mkdirSync(tmp); @@ -2762,10 +2762,16 @@ test('the preview reports a consumer without an origin, one that cannot be clone else process.env.TMPDIR = outer; }); assert.equal(error, undefined, out); - assert.deepEqual(result?.skipped, [{ path: 'acme/noorigin', reason: 'no origin remote' }]); + assert.deepEqual( + result?.skipped.map((s) => s.path), + ['acme/gone', 'acme/noorigin'], + ); assert.ok(has(out, '⚠ acme/noorigin: no origin remote — not previewed'), out); - assert.deepEqual([...(result?.failed ?? [])].sort(), ['acme/gone', 'acme/legacy']); - assert.ok(has(out, '✗ FAILED — clone'), 'the clone that failed is named'); + assert.ok( + has(out, '⚠ acme/gone: the default branch of origin cannot be determined') && has(out, '— not previewed'), + 'an origin that cannot be asked leaves no default branch to clone', + ); + assert.deepEqual(result?.failed, ['acme/legacy']); assert.ok(has(out, 'acme/legacy: ') && has(out, 'still tracks a .copier-answers.yml'), out); assert.deepEqual(result?.clean, ['acme/platform', 'acme/web', 'acme/web/apps/site'], 'the others are previewed'); assert.ok(has(out, join(tmp, 'plx-preview')), 'the scratch is made where TMPDIR says, on every system'); diff --git a/packages/lib/src/consumers.ts b/packages/lib/src/consumers.ts index 71a3d643..3bbb3894 100644 --- a/packages/lib/src/consumers.ts +++ b/packages/lib/src/consumers.ts @@ -1,10 +1,17 @@ // The consumers of the templates: the repos under a directory that take a // version. A consumer is updated in a scratch checkout of its origin's branch, -// never in its own checkout, on the branch the version lands on: the -// operations repo rides main, an app repo rides develop (§ 3 PLX-Delivery), -// and a package repo (its root answers say `publishes_packages`) is -// trunk-based on main (§ 5 PLX-Delivery). A repo without a marker, or that has -// not crossed over, is taken on the branch its checkout is on. +// never in its own checkout, on the branch the version lands on: the default +// branch of its origin, whatever kind of repo it is. A repo without a marker, +// or that has not crossed over, is taken on the branch its checkout is on. +// +// The default branch is read from `origin/HEAD` of the checkout, which costs +// no call, and failing that from origin's own HEAD (`git ls-remote --symref`), +// which works in a fresh CI checkout, where git records no `origin/HEAD`, and +// with any forge. The checkout's record goes stale when the default branch +// changes on the forge, until `git remote set-head origin -a` is run; `update` +// notices when the recorded branch is gone from origin and skips the repo, +// saying so. A repo whose default branch neither tells is skipped, never +// guessed from the branch it is on or from a name. // // `findRepos` finds them for `plx update`: every git repo whose root marker // names a version or lists templates, and every one that carries a marker and @@ -17,41 +24,56 @@ import { type Directory, hasMarker, isOperations } from './model.ts'; export interface Consumer { path: string; rel: string; - /** The branch the version lands on: the expected one, or the checkout's own when the marker names none. */ + /** The branch the version lands on: origin's default branch, or the checkout's own when the marker names none. */ branch: string; - expected?: 'main' | 'develop'; /** The URL of `origin`, which the scratch clone is made from. */ origin?: string; /** Why the consumer is left untouched this run, if it is. */ skipped?: string; } -/** The branch a consumer is updated on; undefined for a repo without a marker, and for one that has not crossed over, whose markers say nothing. */ -export function expectedBranch(repo: Directory): Consumer['expected'] { - if (!repo.declaration || repo.uncrossed) return undefined; - if (isOperations(repo)) return 'main'; - return repo.config?.answers.publishes_packages === true ? 'main' : 'develop'; -} +/** Whether the version lands on origin's default branch: the repo has crossed over to the markers. */ +const landsOnDefault = (repo: Directory): boolean => repo.declaration !== undefined && !repo.uncrossed; /** A consumer of the repo `dir`, named relative to `root`, before its origin is read. */ -const consumerOf = (root: Directory, dir: Directory): Consumer => { - const expected = expectedBranch(dir); - return { - path: dir.path, - rel: relative(root.path, dir.path) || '.', - branch: expected ?? dir.git?.branch ?? 'main', - expected, - }; -}; +const consumerOf = (root: Directory, dir: Directory): Consumer & { onDefault: boolean } => ({ + path: dir.path, + rel: relative(root.path, dir.path) || '.', + branch: dir.git?.branch ?? 'main', + onDefault: landsOnDefault(dir), +}); + +/** What `git remote set-head origin -a` does, to be told to whoever is skipped. */ +const SET_HEAD = '`git remote set-head origin -a` records it'; -/** Each consumer's origin, which the scratch clone is made from; one without is skipped. */ -async function withOrigins(ctx: Context, consumers: Consumer[]): Promise { - for (const c of consumers) { +/** The default branch of origin: as the checkout records it, else as origin says; undefined when neither does. */ +async function defaultBranch(ctx: Context, cwd: string): Promise { + const recorded = ( + await ctx.read('git', ['symbolic-ref', '--short', '-q', 'refs/remotes/origin/HEAD'], { cwd }).catch(() => '') + ).trim(); + if (recorded.startsWith('origin/')) return recorded.slice('origin/'.length); + const said = await ctx.read('git', ['ls-remote', '--symref', 'origin', 'HEAD'], { cwd }).catch(() => ''); + return /^ref: refs\/heads\/(\S+)\s+HEAD$/m.exec(said)?.[1]; +} + +/** Each consumer's origin, which the scratch clone is made from, and the default branch it lands on; one without either is skipped. */ +async function withOrigins(ctx: Context, consumers: (Consumer & { onDefault: boolean })[]): Promise { + const found: Consumer[] = []; + for (const { onDefault, ...c } of consumers) { const origin = (await ctx.read('git', ['remote', 'get-url', 'origin'], { cwd: c.path }).catch(() => '')).trim(); if (origin === '') c.skipped = 'no origin remote'; - else c.origin = origin; + else { + c.origin = origin; + if (onDefault) { + const branch = await defaultBranch(ctx, c.path); + if (branch) c.branch = branch; + else + c.skipped = `the default branch of origin cannot be determined: the checkout records none and origin does not say (is it reachable?); ${SET_HEAD}, or fix the access, then re-run`; + } + } + found.push(c); } - return consumers; + return found; } /** @@ -61,7 +83,7 @@ async function withOrigins(ctx: Context, consumers: Consumer[]): Promise { - const found: Consumer[] = []; + const found: (Consumer & { onDefault: boolean })[] = []; const visit = (dir: Directory) => { const marked = dir.config?.version !== undefined || dir.config?.templates !== undefined; if (dir.git && (marked || (dir.uncrossed && hasMarker(dir)))) found.push(consumerOf(root, dir)); diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 7cd5da7f..c4891870 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -30,7 +30,7 @@ export { } from './changeset.ts'; export { type Compose, declaresHealthcheck, type Mapping, parseCompose } from './compose.ts'; export { filesWithConflictMarkers, hasConflictMarkers, hasUnmergedEntries } from './conflicts.ts'; -export { type Consumer, expectedBranch, findRepos } from './consumers.ts'; +export { type Consumer, findRepos } from './consumers.ts'; export { Context, type Options } from './context.ts'; export { type DeployOptions, diff --git a/packages/lib/src/update.ts b/packages/lib/src/update.ts index 5fe9a229..ebf803ea 100644 --- a/packages/lib/src/update.ts +++ b/packages/lib/src/update.ts @@ -17,8 +17,8 @@ // (`gh api repos/plexus-ms/compendium/releases`): their numbers are the steps, // and their dates are what the interval is measured against. // -// The repo is judged by what origin has on the branch the version lands on -// (consumers.ts), never by the checkout, which may be behind it or on a branch +// The repo is judged by what origin has on the branch the version lands on, its +// default branch (consumers.ts), never by the checkout, which may be behind it or on a branch // of its own. Its markers there are its configuration (sites.ts): the root // marker's `version` is the version the repo is on, and refusing a downgrade, // the interval and readiness all read it. A repo that still tracks a copier @@ -225,7 +225,7 @@ export async function update(ctx: Context, options: UpdateOptions, known?: Known // Without the branch the version lands on there is nothing to take it on. if ((await onOrigin(ctx, repo, consumer.branch)) === false) { - const reason = `origin has no branch \`${consumer.branch}\`, the one the version lands on`; + const reason = `origin has no branch \`${consumer.branch}\`, the default branch the version lands on; if the default branch changed on the forge, \`git remote set-head origin -a\` refreshes what the checkout records`; ctx.say(`⚠ ${name}: ${reason} — skipped`); return { repo: name, version: newest, kind: 'skipped', reason }; } From f5519cc0ee81270725d68dd99fabd07249e0a2d4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:05:14 +0100 Subject: [PATCH 30/91] Index: append the five requirement names of this change; ship regenerates the file at the cut Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/standard-index.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/lib/src/standard-index.json b/packages/lib/src/standard-index.json index 915ff2bb..ebd23ff5 100644 --- a/packages/lib/src/standard-index.json +++ b/packages/lib/src/standard-index.json @@ -249,6 +249,11 @@ "PLX-Updates/LocalConfig", "PLX-Updates/UpdateBot", "PLX-Updates/FromTemplates", - "PLX-Updates/Interval" + "PLX-Updates/Interval", + "PLX-Stack/NoCommittedSecrets", + "PLX-Stack/EnvironmentFile", + "PLX-Stack/EnvironmentParity", + "PLX-Stack/EnvironmentCoverage", + "PLX-Stack/HostnamePort" ] } From 0ff2151a641fe8cec6c26185c05a461907fcbe00 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:05:28 +0100 Subject: [PATCH 31/91] Test: environment findings cite PLX-Stack requirements, SinglePort has three cases, NoCommittedValues is NoCommittedSecrets Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.test.ts | 173 +++++++++++++++++++++++++++----- 1 file changed, 150 insertions(+), 23 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 34966c05..a43f8a8d 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -6,6 +6,7 @@ import { REGULAR, readTree, render, type Tree as Template } from '@plexus-ms/cli import { type Compose, type Mapping, parseCompose } from './compose.ts'; import { Context } from './context.ts'; import { type AppFacts, CHECKS, diagnose, examine, type Facts, type RepoFacts, type StackFacts } from './doctor.ts'; +import type { Environment } from './environments.ts'; import { REQUIREMENT_NAME } from './lints.ts'; import type { MarkerConfig } from './marker.ts'; import { unitsOf } from './model.ts'; @@ -24,7 +25,7 @@ function namesChecked(text: string): string[] { const name = new RegExp(`\`(${REQUIREMENT_NAME})\``, 'g'); return text .split('\n') - .filter((line) => line.startsWith('`plx doctor` checks')) + .filter((line) => line.startsWith('`plx doctor` checks') || line.startsWith('It checks')) .flatMap((line) => [...line.matchAll(name)].map((m) => m[1] ?? '')); } @@ -203,6 +204,21 @@ const onStack = (d?: string[]) => stack(profile, { compose: { services }, ...over }, d); +/** An environment file as the loader returns it. */ +const envFile = (name: string, over: Partial = {}): Environment => ({ + name, + file: `/r/stack/${name}.yaml`, + host: '192.0.2.1', + target: { address: '192.0.2.1' }, + hostname: 'shop.example.com', + env: {}, + secrets: {}, + refused: { env: [], secrets: [] }, + unread: false, + problems: [], + ...over, +}); + const problem = (code: StackProblem['code'], message: string): StackProblem => ({ code, message, stack: 'shop' }); /** For every check: a unit that fails it and nothing else, and what it says. */ @@ -272,7 +288,7 @@ const FAILING: Record Facts; problem: unit: onStack('stateless', { web: web({ env_file: ['.env', '.env.secret'] }) }), problem: /^service `web`: \.env\.secret is loaded, but not marked `required: false`$/, }, - 'PLX-Stack/NoCommittedValues': { + 'PLX-Stack/NoCommittedSecrets': { unit: (deviations = []) => repo({ tracked: ['stack/.env.secret'], @@ -280,6 +296,28 @@ const FAILING: Record Facts; problem: }), problem: /^the source repo tracks `stack\/\.env\.secret`$/, }, + 'PLX-Stack/EnvironmentFile': { + unit: (d) => + stack('stateless', { environments: [envFile('staging', { problems: ['staging.yaml: unknown key `port`'] })] }, d), + problem: /^staging\.yaml: unknown key `port`$/, + }, + 'PLX-Stack/EnvironmentParity': { + unit: (d) => + stack('stateless', { environments: [envFile('production', { env: { A: 'x' } }), envFile('staging')] }, d), + problem: /^staging\.yaml lists no `A` under `env`, which production\.yaml does$/, + }, + 'PLX-Stack/EnvironmentCoverage': { + unit: (d) => + stack( + 'stateless', + { + compose: { ...STATELESS, document: { services: { web: { environment: { A: '${MODE}' } } } } }, + environments: [envFile('staging')], + }, + d, + ), + problem: /^compose\.yaml requires `MODE`, which staging\.yaml does not list under `env`$/, + }, 'PLX-Stack/SinglePort': { unit: onStack('stateless', { web: web({ @@ -292,6 +330,12 @@ const FAILING: Record Facts; problem: unit: onStack('stateless', { web: web(), cache: { image: 'valkey:8', labels: tenant, ports: ['6379'] } }), problem: /^service `cache` publishes `6379` beyond 127\.0\.0\.1$/, }, + 'PLX-Stack/HostnamePort': { + unit: (d) => + stack('stateless', { environments: [envFile('production'), envFile('staging', { hostname: undefined })] }, d), + problem: + /^`hostname` is set in production\.yaml and left out of staging\.yaml; a stack's environment files all set it or none does$/, + }, 'PLX-Stack/Healthcheck': { unit: onStack('stateless', { web: web({ healthcheck: { test: ['NONE'] } }) }), problem: /^service `web` declares no healthcheck with a test of its own$/, @@ -366,6 +410,18 @@ test('a deviation that names no requirement fails, whether a reason is given or ); }); +test('a deviation under the old name of a requirement that was renamed as it moved names the new name', () => { + const old = ['PLX-App', 'NoCommittedValues'].join('/'); + for (const unit of [app({}, [old]), stack('stateless', {}, [old])]) + assert.deepEqual(findings(unit), [ + { + requirement: old, + problem: + 'listed under `deviations`, but no requirement has this name: it moved to `PLX-Stack/NoCommittedSecrets`', + }, + ]); +}); + test('a deviation under the old name of a requirement that moved to PLX-Stack is unknown, and names the new one', () => { // Joined at run time, as above. const moved = (rest: string) => ['PLX-App', rest].join('/'); @@ -470,10 +526,10 @@ test('a stack name that is no project name is a finding of the repo, of no requi assert.deepEqual(findings(repo({ stacks })), [{ problem: 'stacks/Up: `Up` is no Compose project name' }]); }); -test('PLX-Stack/NoCommittedValues: every tracked .env is a finding of the repo, and only a repo with a stack is bound', () => { +test('PLX-Stack/NoCommittedSecrets: every tracked .env is a finding of the repo, and only a repo with a stack is bound', () => { const tracked = ['.env', 'apps/a/.env.secret', 'stack/.env', 'apps/bb/.env.example', 'docs/.envrc']; assert.deepEqual( - named(repo({ tracked }), 'PLX-Stack/NoCommittedValues').map((f) => f.problem), + named(repo({ tracked }), 'PLX-Stack/NoCommittedSecrets').map((f) => f.problem), [ 'the source repo tracks `.env`', 'the source repo tracks `apps/a/.env.secret`', @@ -487,7 +543,7 @@ test('PLX-Stack/NoCommittedValues: every tracked .env is a finding of the repo, stacks: stacksOf({ stacks: [], problems: [{ code: 'no-repo-name', message: 'x' }] }), }); assert.deepEqual( - named(unnamed, 'PLX-Stack/NoCommittedValues').map((f) => f.problem), + named(unnamed, 'PLX-Stack/NoCommittedSecrets').map((f) => f.problem), ['the source repo tracks `stack/.env`'], 'a stack that cannot be named is a stack', ); @@ -1845,9 +1901,9 @@ test('PLX-Stack/AppInStack: of two apps, only the one no stack runs is reported' ); }); -test('PLX-Stack/NoCommittedValues: a tracked .env is reported beside a repo name that is missing', async () => { +test('PLX-Stack/NoCommittedSecrets: a tracked .env is reported beside a repo name that is missing', async () => { const { text } = await webReport((web) => (web['PLEXUS.md'] = MARKER), ['stack/.env']); - assert.deepEqual(text('.', 'PLX-Stack/NoCommittedValues'), ['the source repo tracks `stack/.env`']); + assert.deepEqual(text('.', 'PLX-Stack/NoCommittedSecrets'), ['the source repo tracks `stack/.env`']); assert.equal(text('.').includes(NO_NAME), true); }); @@ -2364,9 +2420,15 @@ const STAGING = async function environmentFindings(files: Tree) { const { of } = await webReport((web) => withStack(web, files)); return of('stack') - .filter((f) => f.requirement === undefined) + .filter((f) => ENVIRONMENT_REQUIREMENTS.includes(f.requirement ?? '')) .map((f) => f.problem); } +const ENVIRONMENT_REQUIREMENTS = [ + 'PLX-Stack/EnvironmentFile', + 'PLX-Stack/EnvironmentParity', + 'PLX-Stack/EnvironmentCoverage', + 'PLX-Stack/HostnamePort', +]; const environmentFiles = (over: Tree = {}): Tree => ({ 'compose.yaml': compose(FROM_ENV), 'production.yaml': PRODUCTION, @@ -2449,19 +2511,17 @@ test('a variable the compose file requires and an environment lists only under s ); }); -test('a compose file that binds PLEXUS_LOOPBACK_PORT needs a hostname in every environment, and one that does not needs none', async () => { - const noHostname = await environmentFindings( +test('PLX-Stack/HostnamePort: the environment files of a stack all set hostname or all leave it out, said once', async () => { + const mixed = await environmentFindings( environmentFiles({ 'staging.yaml': STAGING.replace('hostname: staging.shop.example.com\n', '') }), ); - assert.deepEqual(noHostname, [ - 'staging.yaml has no `hostname`, but compose.yaml binds `PLEXUS_LOOPBACK_PORT`, which needs the public name the proxy serves', - ]); - const unbound = FROM_ENV.replace(/ {4}ports: .*\n/, ''); - const hostnames = await environmentFindings(environmentFiles({ 'compose.yaml': compose(unbound) })); - assert.deepEqual(hostnames.sort(), [ - 'production.yaml has a `hostname`, but compose.yaml binds no `PLEXUS_LOOPBACK_PORT`, so the environment gets no port and no route', - 'staging.yaml has a `hostname`, but compose.yaml binds no `PLEXUS_LOOPBACK_PORT`, so the environment gets no port and no route', + assert.deepEqual(mixed, [ + "`hostname` is set in production.yaml and left out of staging.yaml; a stack's environment files all set it or none does", ]); + const none = await environmentFindings( + environmentFiles({ 'production.yaml': NO_HOSTNAME(PRODUCTION), 'staging.yaml': NO_HOSTNAME(STAGING) }), + ); + assert.deepEqual(none, []); }); /** The variables the compose file requires, as production.yaml is told, over the compose file `text`. */ @@ -2586,13 +2646,32 @@ test('PLX-Stack/SinglePort: without environment files a stack still binds exactl ); }); -test('a stack whose environments have hostnames and whose compose file binds no port is reported once, by the hostname', async () => { +test('PLX-Stack/SinglePort: a stack whose environments have a hostname and binds no port fails once, by SinglePort alone', async () => { const found = await stackFindings(environmentFiles({ 'compose.yaml': compose(NO_PORT) })); assert.deepEqual( - found.map((f) => f.requirement), - [undefined, undefined], + found.map((f) => [f.requirement, f.problem]), + [ + [ + 'PLX-Stack/SinglePort', + 'no service binds `PLEXUS_LOOPBACK_PORT`, which the environments with a `hostname` need', + ], + ], + ); +}); + +test('PLX-Stack/SinglePort: a stack whose environments have no hostname and binds the port fails once, by SinglePort alone', async () => { + const found = await stackFindings( + environmentFiles({ 'production.yaml': NO_HOSTNAME(PRODUCTION), 'staging.yaml': NO_HOSTNAME(STAGING) }), + ); + assert.deepEqual( + found.map((f) => [f.requirement, f.problem]), + [ + [ + 'PLX-Stack/SinglePort', + 'service `web` binds `PLEXUS_LOOPBACK_PORT`, but no environment of the stack has a `hostname`', + ], + ], ); - assert.ok(found.every((f) => /has a `hostname`, but compose.yaml binds no/.test(f.problem))); }); test('PLX-Stack/SinglePort: with environment files a stack that binds two port mappings fails once, by SinglePort', async () => { @@ -2600,7 +2679,7 @@ test('PLX-Stack/SinglePort: with environment files a stack that binds two port m const found = await stackFindings(environmentFiles({ 'compose.yaml': compose(twice) })); const single = found.filter((f) => f.requirement === 'PLX-Stack/SinglePort'); assert.equal(single.length, 1, found.map((f) => f.problem).join('\n')); - assert.equal(found.filter((f) => f.requirement === undefined).length, 0); + assert.equal(found.length, 1); }); test('a name the platform supplies, or listed under both maps, is not also reported as missing from the other files', async () => { @@ -2621,3 +2700,51 @@ test('a malformed host is one finding of the file', async () => { assert.equal(found.length, 1); assert.match(found[0] ?? '', /^staging\.yaml: `host` is not `\[user@\]address\[:port\]`/); }); + +test('the findings on environment files cite their requirements, and a deviation of the stack silences each', async () => { + const cases: [string, Tree, string][] = [ + ['PLX-Stack/EnvironmentFile', environmentFiles({ 'staging.yaml': `${STAGING}port: 1\n` }), 'unknown key'], + ['PLX-Stack/EnvironmentFile', environmentFiles({ 'preview.yml': 'host: 192.0.2.3\n' }), 'name it preview.yaml'], + [ + 'PLX-Stack/EnvironmentFile', + environmentFiles({ 'staging.yaml': STAGING.replace('192.0.2.2', 'ssh://x') }), + '`host` is not', + ], + [ + 'PLX-Stack/EnvironmentParity', + environmentFiles({ 'staging.yaml': STAGING.replace(' MODE: staging\n', '') }), + 'lists no `MODE`', + ], + [ + 'PLX-Stack/EnvironmentCoverage', + environmentFiles({ + 'staging.yaml': STAGING.replace(' MODE: staging\n', ''), + 'production.yaml': PRODUCTION.replace(' MODE: production\n', ''), + }), + 'requires `MODE`', + ], + [ + 'PLX-Stack/HostnamePort', + environmentFiles({ 'staging.yaml': NO_HOSTNAME(STAGING) }), + '`hostname` is set in production.yaml', + ], + ]; + for (const [name, files, text] of cases) { + const { of } = await webReport((web) => withStack(web, files)); + const found = of('stack').filter((f) => f.requirement === name); + assert.ok( + found.some((f) => f.problem.includes(text)), + `${name}: ${text}`, + ); + const silenced = await webReport((web) => { + withStack(web, files); + (web.stack as Tree)['PLEXUS.md'] = + `---\nprofile: stateless\ndeviations: [${name}]\n---\n\n- \`${name}\`: because.\n`; + }); + assert.deepEqual( + silenced.of('stack').filter((f) => f.requirement === name && !f.problem.startsWith('listed under')), + [], + name, + ); + } +}); From 4abc83c7e7b485d10312502f78e3eb3133793b80 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:05:40 +0100 Subject: [PATCH 32/91] Environment findings are the requirements EnvironmentFile, EnvironmentParity, EnvironmentCoverage and HostnamePort; SinglePort has three cases Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.ts | 162 +++++++++++++--------- packages/lib/src/testing/doctor-checks.md | 10 +- 2 files changed, 104 insertions(+), 68 deletions(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 88ab99ab..0297a002 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -42,9 +42,10 @@ // one per file, whatever the marker lists; it names no requirement, and // nothing excludes a file from it. // -// Also of no requirement, and no deviation silences them: what a stack's -// environment files meet (`environmentFindings`), which a stack without -// environment files meets as it is. +// What a stack's environment files meet is four requirements (`environmentFile`, +// `environmentParity`, `environmentCoverage`, `hostnamePort`) and the +// stack's port the one of PLX-Stack/SinglePort, in its three cases; a stack +// without environment files meets the four as it is. // // Also of no requirement, and no deviation silences it: a repo with `stack/` // whose root marker has no `repo` key, which names it (stacks.ts, `no-repo-name`). @@ -361,7 +362,7 @@ function imageRef(compose: Compose, stack: StackFacts): string[] { } /** A tracked `.env` or `.env.secret` of a repo that has a stack. */ -function noCommittedValues(repo: RepoFacts): string[] { +function noCommittedSecrets(repo: RepoFacts): string[] { // A stack the loader could not name (`no-repo-name`) is a stack all the same. const unnamed = repo.stacks?.problems.some((p) => p.code === 'no-repo-name'); if ((repo.stacks?.stacks.length ?? 0) === 0 && !unnamed) return []; @@ -371,18 +372,33 @@ function noCommittedValues(repo: RepoFacts): string[] { } /** - * Exactly one service binds the loopback variable, in one port mapping. A - * stack with environment files may bind none: whether it must is the - * environments' `hostname` (`environmentFindings`), which reports a hostname - * without a port, so that no case is reported twice. + * The stack's port, in three cases. A stack whose environments have a + * `hostname` binds the loopback variable in exactly one port mapping; one + * whose environments have none binds it in none; one without environment + * files binds it in exactly one. An environment that could not be read has no + * known hostname and is left out; where none could be read, or the hostnames + * differ, the stack is held to the first case (`hostnamePort` reports the + * difference), and the second is not applied. */ function singlePort(compose: Compose, stack: StackFacts): string[] { const binders = Object.entries(compose.services) .map(([name, service]) => [name, portsOf(service).filter(bindsLoopbackVar).length] as const) .filter(([, bound]) => bound > 0); const mappings = binders.reduce((sum, [, bound]) => sum + bound, 0); + const read = stack.environments.filter((e) => !e.unread); + const hostnames = read.filter((e) => e.hostname !== undefined).length; + if (read.length > 0 && hostnames === 0) { + const [first] = binders; + return first + ? [`service \`${first[0]}\` binds \`PLEXUS_LOOPBACK_PORT\`, but no environment of the stack has a \`hostname\``] + : []; + } if (binders.length === 0) - return stack.environments.length > 0 ? [] : ['no service binds `PLEXUS_LOOPBACK_PORT`: the stack serves no port']; + return [ + hostnames > 0 + ? 'no service binds `PLEXUS_LOOPBACK_PORT`, which the environments with a `hostname` need' + : 'no service binds `PLEXUS_LOOPBACK_PORT`: the stack serves no port', + ]; if (mappings === 1) return []; const names = binders.map(([name]) => `\`${name}\``).join(', '); const who = binders.length === 1 ? `the service ${names} binds` : `the services ${names} bind`; @@ -505,9 +521,13 @@ export const CHECKS: Readonly> 'PLX-Stack/ImageRef': { binds: 'stack', check: onCompose(imageRef) }, 'PLX-Stack/TenantLabel': { binds: 'stack', check: onCompose(tenantLabel) }, 'PLX-Stack/EnvFileLoad': { binds: 'stack', check: onCompose(envFileLoad) }, - 'PLX-Stack/NoCommittedValues': { binds: 'repo', check: noCommittedValues }, + 'PLX-Stack/NoCommittedSecrets': { binds: 'repo', check: noCommittedSecrets }, + 'PLX-Stack/EnvironmentFile': { binds: 'stack', check: environmentFile }, + 'PLX-Stack/EnvironmentParity': { binds: 'stack', check: environmentParity }, + 'PLX-Stack/EnvironmentCoverage': { binds: 'stack', check: onCompose(environmentCoverage) }, 'PLX-Stack/SinglePort': { binds: 'stack', check: onCompose(singlePort) }, 'PLX-Stack/LoopbackPort': { binds: 'stack', check: onCompose(loopbackPort) }, + 'PLX-Stack/HostnamePort': { binds: 'stack', check: hostnamePort }, 'PLX-Stack/Healthcheck': { binds: 'stack', check: onCompose(healthcheck) }, 'PLX-Stack/Stateless/NoState': { binds: 'stack', profile: 'stateless', check: onCompose(noState) }, 'PLX-Stack/Stateful/MigrateService': { binds: 'stack', profile: 'stateful', check: onCompose(migrateService) }, @@ -515,72 +535,80 @@ export const CHECKS: Readonly> }; /** - * What a stack's environment files must meet, none of it a requirement yet - * and so a finding of none, which no deviation silences, in four groups that - * the requirements will take one to one. A stack without environment files - * meets all of it. (1) The shape: each file is usable, its keys, pointers and - * name, and no `.yml` stands for one (the loader's `problems`, one - * line per bad value). (2) The same names across the files: the files list - * the same names under `env` and under `secrets`, one line for each name an - * environment lacks, naming the first that has it; a file that could not be - * read is left out. (3) Every variable the compose file requires by - * interpolation (`requiredVariables`) is listed under `env` of each (compose - * fills `${…}` from `.env` alone), but for the platform's - * (`PLATFORM_VARIABLES`). (4) An environment has a `hostname` exactly where - * the compose file binds `PLEXUS_LOOPBACK_PORT`, as it gets a port and a route - * only then. + * PLX-Stack/EnvironmentFile: each environment file is usable, its keys, the + * form of `host`, strings under `env`, pointers under `secrets`, its name, no + * name in both maps and none the platform supplies (the loader's `problems`, + * one line per bad value), and no `.yml` stands for one. */ -function environmentFindings(stack: StackFacts): string[] { - const { compose } = stack; - const environments = stack.environments; - const read = environments.filter((e) => !e.unread); - // The shape of the files, their names and keys and pointers. - const problems = [ +function environmentFile(stack: StackFacts): string[] { + return [ ...stack.problems.filter((p) => p.code === 'bad-environment-file').map((p) => p.message), - ...environments.flatMap((e) => e.problems), + ...stack.environments.flatMap((e) => e.problems), ]; - // The same names across the files. - const listed = (e: Environment, key: 'env' | 'secrets') => [...Object.keys(e[key]), ...e.refused[key]]; - // A name the platform supplies or one listed under both maps has its finding already. +} + +/** The names an environment lists under `env` or `secrets`, whose value may have been refused. */ +const listed = (e: Environment, key: 'env' | 'secrets') => [...Object.keys(e[key]), ...e.refused[key]]; + +/** The environments of which something is known: a file that could not be read at all is left out of every comparison. */ +const readEnvironments = (stack: StackFacts): Environment[] => stack.environments.filter((e) => !e.unread); + +/** + * PLX-Stack/EnvironmentParity: the files list the same names under `env` and + * under `secrets`, one line for each name an environment lacks, naming the + * first that has it. A name the platform supplies, or one listed under both + * maps, has its finding in EnvironmentFile already. + */ +function environmentParity(stack: StackFacts): string[] { + const read = readEnvironments(stack); const doubled = new Set([ ...PLATFORM_VARIABLES, ...read.flatMap((e) => listed(e, 'env').filter((n) => listed(e, 'secrets').includes(n))), ]); - for (const key of ['env', 'secrets'] as const) { - const names = [...new Set(read.flatMap((e) => listed(e, key)))].filter((n) => !doubled.has(n)); - for (const name of names) { + const problems: string[] = []; + for (const key of ['env', 'secrets'] as const) + for (const name of new Set(read.flatMap((e) => listed(e, key)))) { const holder = read.find((e) => listed(e, key).includes(name)); for (const e of read) - if (holder && !listed(e, key).includes(name)) + if (holder && !doubled.has(name) && !listed(e, key).includes(name)) problems.push(`${e.name}.yaml lists no \`${name}\` under \`${key}\`, which ${holder.name}.yaml does`); } - } - if (compose && read.length > 0) { - // Every required variable listed. - for (const variable of requiredVariables(compose).filter((v) => !PLATFORM_VARIABLES.includes(v))) - for (const e of read) - if (!listed(e, 'env').includes(variable)) - problems.push( - variable in e.secrets - ? `compose.yaml requires \`${variable}\`, which ${e.name}.yaml lists under \`secrets\` only; compose fills \`\${…}\` from \`.env\`, and a secret reaches a container through \`env_file\`, so list it under \`env\`` - : `compose.yaml requires \`${variable}\`, which ${e.name}.yaml does not list under \`env\``, - ); - // A hostname exactly where the port is bound. - const binds = Object.values(compose.services).some((service) => portsOf(service).some(bindsLoopbackVar)); - for (const e of read) { - if (binds && e.hostname === undefined) - problems.push( - `${e.name}.yaml has no \`hostname\`, but compose.yaml binds \`PLEXUS_LOOPBACK_PORT\`, which needs the public name the proxy serves`, - ); - if (!binds && e.hostname !== undefined) - problems.push( - `${e.name}.yaml has a \`hostname\`, but compose.yaml binds no \`PLEXUS_LOOPBACK_PORT\`, so the environment gets no port and no route`, - ); - } - } return problems; } +/** + * PLX-Stack/EnvironmentCoverage: every variable the compose file interpolates + * in a value (`requiredVariables`, keys not read), but for the platform's + * (`PLATFORM_VARIABLES`), is listed under `env` of each environment. Compose + * fills `${…}` from `.env` alone, so a name only under `secrets` is not + * covered. + */ +function environmentCoverage(compose: Compose, stack: StackFacts): string[] { + return requiredVariables(compose) + .filter((v) => !PLATFORM_VARIABLES.includes(v)) + .flatMap((variable) => + readEnvironments(stack) + .filter((e) => !listed(e, 'env').includes(variable)) + .map((e) => + variable in e.secrets + ? `compose.yaml requires \`${variable}\`, which ${e.name}.yaml lists under \`secrets\` only; compose fills \`\${…}\` from \`.env\`, and a secret reaches a container through \`env_file\`, so list it under \`env\`` + : `compose.yaml requires \`${variable}\`, which ${e.name}.yaml does not list under \`env\``, + ), + ); +} + +/** PLX-Stack/HostnamePort: the files all set `hostname` or all leave it out. */ +function hostnamePort(stack: StackFacts): string[] { + const read = readEnvironments(stack); + const set = read.filter((e) => e.hostname !== undefined).map((e) => `${e.name}.yaml`); + const out = read.filter((e) => e.hostname === undefined).map((e) => `${e.name}.yaml`); + return set.length > 0 && out.length > 0 + ? [ + `\`hostname\` is set in ${set.join(', ')} and left out of ${out.join(', ')}; a stack's environment files all set it or none does`, + ] + : []; +} + /** * What the markers as configuration must meet (sites.ts): the root's `version` * is the `plx` pin's, no other marker has one, and no key is answered in two @@ -648,12 +676,10 @@ const MOVED_TO_STACK = new Set([ 'ComposeDelivery', 'EnvFiles', 'EnvFileLoad', - 'NoCommittedValues', 'ReservedPrefix', 'ImageRef', 'SinglePort', 'LoopbackPort', - 'PathPrefix', 'Healthcheck', 'Stateless/NoState', 'Stateful/BackupLabel', @@ -667,9 +693,14 @@ const MOVED_TO_STACK = new Set([ 'Stateful/Seed', ]); +/** What a requirement that was renamed as it moved is called now. */ +const RENAMED_ON_MOVE: Readonly> = { NoCommittedValues: 'NoCommittedSecrets' }; + function movedTo(name: string): string | undefined { const rest = name.startsWith('PLX-App/') ? name.slice('PLX-App/'.length) : undefined; - return rest !== undefined && MOVED_TO_STACK.has(rest) ? `PLX-Stack/${rest}` : undefined; + if (rest === undefined) return undefined; + if (rest in RENAMED_ON_MOVE) return `PLX-Stack/${RENAMED_ON_MOVE[rest]}`; + return MOVED_TO_STACK.has(rest) ? `PLX-Stack/${rest}` : undefined; } function versionOfRoot(repo: RepoFacts): string[] { @@ -761,7 +792,6 @@ function diagnoseUnit(unit: Facts, known: Set): UnitReport { if (deviations.includes(name)) continue; for (const problem of run(c, unit, profile)) findings.push({ requirement: name, problem }); } - if (unit.kind === 'stack') for (const problem of environmentFindings(unit)) findings.push({ problem }); if (isRepo(unit)) { for (const problem of repoNaming(unit)) findings.push({ problem }); for (const file of unit.conflicted ?? []) findings.push({ problem: `\`${file}\` holds a conflict marker` }); diff --git a/packages/lib/src/testing/doctor-checks.md b/packages/lib/src/testing/doctor-checks.md index dfe63269..ae495645 100644 --- a/packages/lib/src/testing/doctor-checks.md +++ b/packages/lib/src/testing/doctor-checks.md @@ -20,9 +20,15 @@ set to a compendium checkout it reads the pages themselves instead. `plx doctor` checks `PLX-Stack/Layout` and `PLX-Stack/AppInStack`; of `PLX-Stack/Compose` that every stack has its `compose.yaml`; of `PLX-Stack/ImageRef` that every image naming an app of the repo has that form, with or without an error message, and every other image holds no interpolation; and of `PLX-Stack/TenantLabel` that every service carries a `plexus.tenant` label with a value, not that the value is the tenant's slug. -`plx doctor` checks `PLX-Stack/EnvFileLoad` on the service that publishes the loopback port and on every service that runs the image of one of the stack's apps, and of `PLX-Stack/NoCommittedValues` that the repo tracks no `.env` and no `.env.secret`. +`plx doctor` checks `PLX-Stack/EnvFileLoad` on the service that publishes the loopback port and on every service that runs the image of one of the stack's apps, and of `PLX-Stack/NoCommittedSecrets` that the repo tracks no `.env` and no `.env.secret`. -`plx doctor` checks of `PLX-Stack/SinglePort` that exactly one service binds `PLEXUS_LOOPBACK_PORT`, in exactly one port mapping (none, where the stack has environment files, whose `hostname` decides whether the port is bound), not that it speaks plain HTTP, and checks `PLX-Stack/LoopbackPort`. +It checks `PLX-Stack/EnvironmentFile`, of `host` its form and not that the host answers, refusing a number or a boolean under `env` with the advice to quote it, and checks `PLX-Stack/EnvironmentParity`. + +It checks of `PLX-Stack/EnvironmentCoverage` that every variable interpolated in a value of the compose file is listed under `env` of every environment file; it reads no key of the compose file, and not how a secret reaches a container. + +`plx doctor` checks of `PLX-Stack/SinglePort` that a stack whose environments have a `hostname` binds `PLEXUS_LOOPBACK_PORT` in exactly one port mapping, a stack whose environments have none binds it in none, and a stack without environment files binds it in exactly one, not that the service speaks plain HTTP. + +It checks `PLX-Stack/LoopbackPort` and `PLX-Stack/HostnamePort`. `plx doctor` checks of `PLX-Stack/Healthcheck` that each of those services declares a `healthcheck` with a test of its own that is not disabled. From 75afb4fb5068211b72e6da3f7f94a2d96d2f725c Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:20:50 +0100 Subject: [PATCH 33/91] Test: host forms with ssh options, a cyclic alias, one fault one finding, a secret not interpolated, released names Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.test.ts | 64 +++++++++++++++++++- packages/lib/src/stacks.test.ts | 100 +++++++++++++++++++++++++++----- 2 files changed, 149 insertions(+), 15 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index a43f8a8d..9fdbe89f 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -2505,10 +2505,11 @@ test('a variable the compose file requires and an environment lists only under s const found = await environmentFindings(swapped); assert.ok( found.includes( - 'compose.yaml requires `MODE`, which production.yaml lists under `secrets` only; compose fills `${…}` from `.env`, and a secret reaches a container through `env_file`, so list it under `env`', + 'compose.yaml requires `MODE`, which production.yaml lists under `secrets` only; a secret is not interpolated: a service reads it from its environment, which `env_file` fills, so interpolate no secret', ), found.join('\n'), ); + assert.ok(!found.some((p) => p.includes('list it under `env`')), 'never to commit a secret as a plain value'); }); test('PLX-Stack/HostnamePort: the environment files of a stack all set hostname or all leave it out, said once', async () => { @@ -2611,7 +2612,7 @@ test('a name under both env and secrets, and a name the platform supplies, are f test('a `.yml` file in a stack directory is a finding of the stack', async () => { const found = await environmentFindings(environmentFiles({ 'preview.yml': 'host: 192.0.2.3\n' })); - assert.deepEqual(found, ['stack/preview.yml: name it preview.yaml']); + assert.deepEqual(found, ['preview.yml: name it preview.yaml']); }); test('an environment that could not be read is left out of the comparisons with the others', async () => { @@ -2748,3 +2749,62 @@ test('the findings on environment files cite their requirements, and a deviation ); } }); + +test('one fault, one finding: env that is no map, an empty hostname, and hostnames that differ', async () => { + const noMap = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace(/env:\n {2}MODE: staging\n/, 'env: [a]\n') }), + ); + assert.equal(noMap.length, 1, noMap.join('\n')); + assert.match(noMap[0] ?? '', /^staging\.yaml: `env` is not a map/); + const noSecretsMap = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace(/secrets:\n.*\n/, 'secrets: x\n') }), + ); + assert.equal(noSecretsMap.length, 1, noSecretsMap.join('\n')); + const empty = await stackFindings( + environmentFiles({ 'staging.yaml': STAGING.replace(/hostname: .*\n/, 'hostname: ""\n') }), + ); + assert.deepEqual( + empty.map((f) => [f.requirement, f.problem]), + [['PLX-Stack/EnvironmentFile', 'staging.yaml: `hostname` is not a non-empty string']], + ); + const mixed = await stackFindings( + environmentFiles({ 'compose.yaml': compose(NO_PORT), 'staging.yaml': NO_HOSTNAME(STAGING) }), + ); + assert.deepEqual( + mixed.map((f) => f.requirement), + ['PLX-Stack/HostnamePort'], + ); +}); + +test('a cyclic alias in compose.yaml is reported as a compose file that cannot be read, and doctor survives it', async () => { + const { of } = await webReport((web) => + withStack(web, { + 'compose.yaml': `x-a: &a\n self: *a\nservices:\n web:\n image: ghcr.io/acme/site:\${PLEXUS_TAG:?set}\n labels: *a\n`, + }), + ); + const found = of('stack').filter((f) => f.requirement === 'PLX-Stack/Compose'); + assert.equal(found.length, 1); + assert.match(found[0]?.problem ?? '', /aliases form a cycle/); +}); + +test('a deviation under a name released in an earlier version is told what it is now, or that it is gone', () => { + const stale = new Set([...KNOWN, 'PLX-Stack/NoCommittedValues', 'PLX-Stack/PathPrefix']); + const old = ['PLX-Stack', 'NoCommittedValues'].join('/'); + const gone = ['PLX-Stack', 'PathPrefix'].join('/'); + const found = diagnose([stack('stateless', {}, [old, gone])], stale).units[0]?.findings; + assert.deepEqual(found, [ + { + requirement: old, + problem: 'listed under `deviations`, but no requirement has this name: it is now `PLX-Stack/NoCommittedSecrets`', + }, + { requirement: gone, problem: 'listed under `deviations`, but no requirement has this name' }, + ]); + // The old name silences nothing: the check of the new name still runs. + const tracked = repo({ + tracked: ['stack/.env'], + marker: { declaration: { deviations: [old], body: reasoned([old]) } }, + }); + assert.ok( + diagnose([tracked], stale).units[0]?.findings.some((f) => f.requirement === 'PLX-Stack/NoCommittedSecrets'), + ); +}); diff --git a/packages/lib/src/stacks.test.ts b/packages/lib/src/stacks.test.ts index f1963e07..bcf7cb21 100644 --- a/packages/lib/src/stacks.test.ts +++ b/packages/lib/src/stacks.test.ts @@ -426,6 +426,7 @@ test("a stack's environments are its `.yaml` files but the compose files, env: { MODE: 'production' }, secrets: { TOKEN: 'op://acme/shop/token' }, refused: { env: [], secrets: [] }, + invalid: [], unread: false, problems: [], }, @@ -437,6 +438,7 @@ test("a stack's environments are its `.yaml` files but the compose files, env: { MODE: 'staging', RETRIES: '3', DEBUG: 'true' }, secrets: {}, refused: { env: [], secrets: [] }, + invalid: [], unread: false, problems: [], }, @@ -560,28 +562,36 @@ test('a `.yml` file in a stack directory is a problem of the stack, naming assert.deepEqual(repo.stacks[0]?.environments, []); assert.deepEqual(codes(repo), ['bad-environment-file', 'bad-environment-file']); assert.deepEqual(repo.problems.map((p) => p.message).sort(), [ - 'stack/compose.dev.yml: name it compose.dev.yaml', - 'stack/production.yml: name it production.yaml', + 'compose.dev.yml: name it compose.dev.yaml', + 'production.yml: name it production.yaml', ]); assert.equal(repo.problems[0]?.stack, 'shop'); }); +/** The environment a `host` value gives, written as a YAML scalar by JSON, which quotes whatever it holds. */ +const withHost = async (host: string) => + (await environmentsOf({ 'staging.yaml': `host: ${JSON.stringify(host)}\n` }))[0]; + test('`host` is an SSH destination, `[user@]address[:port]`, returned as written and parsed, absence being absence', async () => { const cases: [string, Record][] = [ ['192.0.2.1', { address: '192.0.2.1' }], ['shop.example.com', { address: 'shop.example.com' }], + ['localhost', { address: 'localhost' }], + ['a-b.c-d.example.com', { address: 'a-b.c-d.example.com' }], ['192.0.2.1:22', { address: '192.0.2.1', port: 22 }], + ['255.255.255.255', { address: '255.255.255.255' }], ['deploy@192.0.2.10:2222', { address: '192.0.2.10', user: 'deploy', port: 2222 }], ['deploy@shop.example.com', { address: 'shop.example.com', user: 'deploy' }], + ['de.ploy_1@shop.example.com:1', { address: 'shop.example.com', user: 'de.ploy_1', port: 1 }], ['2001:db8::1', { address: '2001:db8::1' }], + ['::1', { address: '::1' }], ['deploy@2001:db8::1', { address: '2001:db8::1', user: 'deploy' }], ['[2001:db8::1]', { address: '2001:db8::1' }], ['[2001:db8::1]:2222', { address: '2001:db8::1', port: 2222 }], ['deploy@[2001:db8::1]:65535', { address: '2001:db8::1', user: 'deploy', port: 65535 }], - ['192.0.2.1:1', { address: '192.0.2.1', port: 1 }], ]; for (const [host, target] of cases) { - const [environment] = await environmentsOf({ 'staging.yaml': `host: "${host}"\n` }); + const environment = await withHost(host); assert.deepEqual(environment?.problems, [], host); assert.equal(environment?.host, host); assert.deepEqual(environment?.target, target, host); @@ -590,27 +600,66 @@ test('`host` is an SSH destination, `[user@]address[:port]`, returned as written test('a `host` that is no SSH destination is one problem naming the file and showing the form, and no host', async () => { const bad = [ - '@192.0.2.1', - 'deploy@', + // ssh options, in each position + '-Jevil.example.com', + '-oProxyCommand=x@h', + '-u@host', + 'u@-h', + 'u@-h:22', + 'u@[-::1]', + '-', + '.', + '-a.example.com', + 'a-.example.com', + 'a.-b.example.com', + // names and numbers + '999.999.999.999', + '1.2.3', + '1.2.3.4.5', + '01.2.3.256', + 'a..b', + 'host.', + '.host', + // ports '192.0.2.1:', ':22', '192.0.2.1:0', '192.0.2.1:65536', '192.0.2.1:ab', '192.0.2.1:-1', - '192.0.2.1 ', - '192.0.2.1 x', - 'ssh://192.0.2.1', - '192.0.2.1/path', + '192.0.2.1:22:33', + // user + '@192.0.2.1', + 'deploy@', 'a@b@c', + 'de ploy@192.0.2.1', + // brackets + '[:]', + '[]', '[2001:db8::1', '[2001:db8::1]x', '[2001:db8::1]:', - '[]', - 'de ploy@192.0.2.1', + '[2001:db8::1]:ab', + '[192.0.2.1]', + '[shop.example.com]:22', + '2001:db8::1]', + // characters no name has + '192.0.2.1 ', + '192.0.2.1 x', + 'a b', + 'h;reboot', + 'u;x@h', + '$(id)', + 'h$(id).example.com', + '`id`', + '"x', + "'x", + 'ssh://192.0.2.1', + '192.0.2.1/path', + 'h\\n', ]; for (const host of bad) { - const [environment] = await environmentsOf({ 'staging.yaml': `host: "${host}"\n` }); + const environment = await withHost(host); assert.equal(environment?.problems.length, 1, host); assert.match( environment?.problems[0] ?? '', @@ -621,3 +670,28 @@ test('a `host` that is no SSH destination is one problem naming the file and sho assert.equal(environment?.target, undefined, host); } }); + +test('a value that makes part of a file unusable is named in `invalid`, so that the comparisons leave that part out', async () => { + const cases: [string, string][] = [ + ['hostname: ""\n', 'hostname'], + ['hostname: 3\n', 'hostname'], + ['env: [a]\n', 'env'], + ['secrets: x\n', 'secrets'], + ]; + for (const [text, key] of cases) { + const [environment] = await environmentsOf({ 'staging.yaml': `host: 192.0.2.1\n${text}` }); + assert.deepEqual(environment?.invalid, [key], text); + assert.equal(environment?.problems.length, 1, text); + } + const [fine] = await environmentsOf({ 'staging.yaml': 'host: 192.0.2.1\n' }); + assert.deepEqual(fine?.invalid, []); +}); + +test('a compose file whose aliases form a cycle is a bad compose file, which compose refuses too', async () => { + const repo = await load({ + stack: { 'compose.yaml': 'x-a: &a\n self: *a\nservices:\n web:\n image: ghcr.io/acme/shop:${PLEXUS_TAG}\n' }, + apps: { shop: dockerfile }, + }); + assert.deepEqual(codes(repo), ['bad-compose']); + assert.match(repo.problems[0]?.message ?? '', /aliases form a cycle/); +}); From 17190a4859cc1fd59aa959d9107c7ccd28d8a591 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:22:21 +0100 Subject: [PATCH 34/91] host refuses ssh options and takes a DNS name, IPv4 or IPv6 address; cyclic aliases are refused; one fault is one finding; renamed and removed names are told Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/compose.ts | 24 ++++++++++++ packages/lib/src/doctor.test.ts | 1 + packages/lib/src/doctor.ts | 47 ++++++++++++++++------- packages/lib/src/environments.ts | 64 ++++++++++++++++++++++---------- packages/lib/src/stacks.test.ts | 4 +- packages/lib/src/stacks.ts | 8 ++-- 6 files changed, 108 insertions(+), 40 deletions(-) diff --git a/packages/lib/src/compose.ts b/packages/lib/src/compose.ts index a869f8d0..49e6c402 100644 --- a/packages/lib/src/compose.ts +++ b/packages/lib/src/compose.ts @@ -32,6 +32,28 @@ export interface Compose { export const isMapping = (value: unknown): value is Mapping => value !== null && typeof value === 'object' && !Array.isArray(value); +/** The path of a node of the document that holds itself through its aliases, or none; each node is visited once. */ +function aliasCycle(doc: unknown): string | undefined { + const done = new Set(); + const path: string[] = []; + const onPath = new Set(); + const visit = (node: unknown): string | undefined => { + if (node === null || typeof node !== 'object' || done.has(node)) return undefined; + if (onPath.has(node)) return path.join('.') || 'the root'; + onPath.add(node); + for (const [key, child] of Object.entries(node)) { + path.push(key); + const found = visit(child); + path.pop(); + if (found !== undefined) return found; + } + onPath.delete(node); + done.add(node); + return undefined; + }; + return visit(doc); +} + /** What a YAML error says, in one line: `not valid YAML: `. */ export const yamlError = (error: unknown): string => `not valid YAML: ${(error as Error).message.split('\n')[0]?.replace(/:$/, '')}`; @@ -47,6 +69,8 @@ export function parseCompose(text: string, path: string): Compose { } catch (error) { throw new UsageError(`${path}: ${yamlError(error)}`); } + const cycle = aliasCycle(doc); + if (cycle) throw new UsageError(`${path}: aliases form a cycle at ${cycle}; compose refuses such a file`); const declared = isMapping(doc) && isMapping(doc.services) ? doc.services : {}; const written: Record = {}; for (const [name, service] of Object.entries(declared)) if (isMapping(service)) written[name] = service; diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 9fdbe89f..097a4547 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -214,6 +214,7 @@ const envFile = (name: string, over: Partial = {}): Environment => env: {}, secrets: {}, refused: { env: [], secrets: [] }, + invalid: [], unread: false, problems: [], ...over, diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 0297a002..cac85802 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -376,17 +376,18 @@ function noCommittedSecrets(repo: RepoFacts): string[] { * `hostname` binds the loopback variable in exactly one port mapping; one * whose environments have none binds it in none; one without environment * files binds it in exactly one. An environment that could not be read has no - * known hostname and is left out; where none could be read, or the hostnames - * differ, the stack is held to the first case (`hostnamePort` reports the - * difference), and the second is not applied. + * known hostname and is left out; where none could be read, the stack is held + * to the first case, and where the hostnames differ, `hostnamePort` reports it + * and this check says nothing of the stack. */ function singlePort(compose: Compose, stack: StackFacts): string[] { const binders = Object.entries(compose.services) .map(([name, service]) => [name, portsOf(service).filter(bindsLoopbackVar).length] as const) .filter(([, bound]) => bound > 0); const mappings = binders.reduce((sum, [, bound]) => sum + bound, 0); - const read = stack.environments.filter((e) => !e.unread); + const read = hostnameKnown(stack); const hostnames = read.filter((e) => e.hostname !== undefined).length; + if (hostnames > 0 && hostnames < read.length) return []; if (read.length > 0 && hostnames === 0) { const [first] = binders; return first @@ -550,7 +551,7 @@ function environmentFile(stack: StackFacts): string[] { /** The names an environment lists under `env` or `secrets`, whose value may have been refused. */ const listed = (e: Environment, key: 'env' | 'secrets') => [...Object.keys(e[key]), ...e.refused[key]]; -/** The environments of which something is known: a file that could not be read at all is left out of every comparison. */ +/** The environments of which something is known: a file that could not be read at all is left out of every comparison, and a part of one whose value is unusable (`invalid`) out of the comparison of that part. */ const readEnvironments = (stack: StackFacts): Environment[] => stack.environments.filter((e) => !e.unread); /** @@ -566,13 +567,15 @@ function environmentParity(stack: StackFacts): string[] { ...read.flatMap((e) => listed(e, 'env').filter((n) => listed(e, 'secrets').includes(n))), ]); const problems: string[] = []; - for (const key of ['env', 'secrets'] as const) - for (const name of new Set(read.flatMap((e) => listed(e, key)))) { - const holder = read.find((e) => listed(e, key).includes(name)); - for (const e of read) + for (const key of ['env', 'secrets'] as const) { + const of = read.filter((e) => !e.invalid.includes(key)); + for (const name of new Set(of.flatMap((e) => listed(e, key)))) { + const holder = of.find((e) => listed(e, key).includes(name)); + for (const e of of) if (holder && !doubled.has(name) && !listed(e, key).includes(name)) problems.push(`${e.name}.yaml lists no \`${name}\` under \`${key}\`, which ${holder.name}.yaml does`); } + } return problems; } @@ -588,18 +591,22 @@ function environmentCoverage(compose: Compose, stack: StackFacts): string[] { .filter((v) => !PLATFORM_VARIABLES.includes(v)) .flatMap((variable) => readEnvironments(stack) - .filter((e) => !listed(e, 'env').includes(variable)) + .filter((e) => !e.invalid.includes('env') && !listed(e, 'env').includes(variable)) .map((e) => variable in e.secrets - ? `compose.yaml requires \`${variable}\`, which ${e.name}.yaml lists under \`secrets\` only; compose fills \`\${…}\` from \`.env\`, and a secret reaches a container through \`env_file\`, so list it under \`env\`` + ? `compose.yaml requires \`${variable}\`, which ${e.name}.yaml lists under \`secrets\` only; a secret is not interpolated: a service reads it from its environment, which \`env_file\` fills, so interpolate no secret` : `compose.yaml requires \`${variable}\`, which ${e.name}.yaml does not list under \`env\``, ), ); } +/** The environments whose `hostname`, set or left out, is known: its value is usable. */ +const hostnameKnown = (stack: StackFacts): Environment[] => + readEnvironments(stack).filter((e) => !e.invalid.includes('hostname')); + /** PLX-Stack/HostnamePort: the files all set `hostname` or all leave it out. */ function hostnamePort(stack: StackFacts): string[] { - const read = readEnvironments(stack); + const read = hostnameKnown(stack); const set = read.filter((e) => e.hostname !== undefined).map((e) => `${e.name}.yaml`); const out = read.filter((e) => e.hostname === undefined).map((e) => `${e.name}.yaml`); return set.length > 0 && out.length > 0 @@ -696,6 +703,15 @@ const MOVED_TO_STACK = new Set([ /** What a requirement that was renamed as it moved is called now. */ const RENAMED_ON_MOVE: Readonly> = { NoCommittedValues: 'NoCommittedSecrets' }; +/** Requirements of a version the index of this plx still holds that the compendium no longer has: a deviation under them is unknown whatever the index says. */ +const REMOVED = new Set(['PLX-Stack/PathPrefix']); + +/** What a released `PLX-Stack/…` name is called now, where it was renamed; the `PLX-App/…` form is `movedTo`'s. */ +function renamedInStack(name: string): string | undefined { + const rest = name.startsWith('PLX-Stack/') ? name.slice('PLX-Stack/'.length) : undefined; + return rest !== undefined && rest in RENAMED_ON_MOVE ? `PLX-Stack/${RENAMED_ON_MOVE[rest]}` : undefined; +} + function movedTo(name: string): string | undefined { const rest = name.startsWith('PLX-App/') ? name.slice('PLX-App/'.length) : undefined; if (rest === undefined) return undefined; @@ -780,7 +796,12 @@ function diagnoseUnit(unit: Facts, known: Set): UnitReport { requirement: name, problem: `listed under \`deviations\`, but no requirement has this name: it moved to \`${moved}\``, }); - else if (!known.has(name)) + else if (renamedInStack(name)) + findings.push({ + requirement: name, + problem: `listed under \`deviations\`, but no requirement has this name: it is now \`${renamedInStack(name)}\``, + }); + else if (!known.has(name) || REMOVED.has(name)) findings.push({ requirement: name, problem: 'listed under `deviations`, but no requirement has this name' }); else if (!reasonGiven(declaration?.body ?? '', name)) findings.push({ diff --git a/packages/lib/src/environments.ts b/packages/lib/src/environments.ts index 2e1e8fe1..85dc613b 100644 --- a/packages/lib/src/environments.ts +++ b/packages/lib/src/environments.ts @@ -13,12 +13,19 @@ // no name has a meaning: no code compares one with a literal. The file is a // YAML map with exactly four keys: // host the machine as an SSH destination, `[user@]address[:port]`, as in -// `deploy@192.0.2.10:2222`; required. The address is a name or an -// IPv4 or IPv6 address, the last in brackets where a port follows -// and bare otherwise. It is returned as written (`host`) and -// parsed (`target`: the address, the user and the port where given, -// absent where not; the default user and port are the connecting -// side's to name, not this file's) +// `deploy@192.0.2.10:2222`; required. As checked: the user, where +// given, starts with a letter, a digit or `_` and holds letters, +// digits, `.`, `_` and `-` (so never an ssh option); the address is +// a DNS name (labels of letters, digits and `-`, none starting or +// ending with `-`, separated by single dots, no trailing dot), or an +// IPv4 address (`net.isIP`; a name with the shape of one that is +// none is refused), or an IPv6 address (`net.isIP`), bare, or in +// brackets, which it needs where a port follows and which hold +// nothing else; the port is a number from 1 to 65535. It is +// returned as written (`host`) and parsed (`target`: the address +// without brackets, the user and the port where given, absent where +// not; the default user and port are the connecting side's to name, +// not this file's) // hostname the public name the proxy serves, a non-empty string; optional, // and without it the environment gets no loopback port and no route // env a map of names to strings; absent reads as empty. A value that @@ -46,6 +53,7 @@ // value of the document, as compose does (services, top-level `volumes` and // `networks`, `x-` fields, lists), and no key. Compose fills them from `.env`, // that is from `env`, and never from `.env.secret`. +import { isIP } from 'node:net'; import { join } from 'node:path'; import { parse } from 'yaml'; import { type Compose, isMapping, yamlError } from './compose.ts'; @@ -69,14 +77,25 @@ export interface SshTarget { /** The form of `host`, shown in the finding. */ const HOST_FORM = '`[user@]address[:port]`, as in `deploy@192.0.2.10:2222`'; -/** A `host` parsed, or why it is no SSH destination. */ +/** What a user name is: it never starts with `-`, which ssh would read as an option. */ +const USER = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/; + +/** What a DNS label is: letters, digits and `-`, not starting or ending with `-`. */ +const LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/; + +/** The address of a `host` that is none of IPv6: an IPv4 address (`net.isIP`) or a DNS name, and a name never has the shape of an IPv4 address. */ +function addressProblem(address: string): string | undefined { + if (isIP(address) === 4) return undefined; + if (/^[0-9.]+$/.test(address)) return 'it has the shape of an IPv4 address and is none'; + return address.split('.').every((label) => LABEL.test(label)) ? undefined : 'it is no DNS name, IPv4 or IPv6 address'; +} + +/** A `host` parsed, or why it is no SSH destination. The grammar is in the header. */ export function parseHost(host: string): SshTarget | string { - if (/\s/.test(host)) return 'it holds whitespace'; - if (host.includes('/')) return 'it holds a scheme or a path'; const at = host.lastIndexOf('@'); const user = at < 0 ? undefined : host.slice(0, at); const rest = host.slice(at + 1); - if (user !== undefined && (user === '' || /[@:]/.test(user))) return 'the user is empty or holds `@` or `:`'; + if (user !== undefined && !USER.test(user)) return 'the user is no user name'; let address = rest; let port: string | undefined; if (rest.startsWith('[')) { @@ -84,18 +103,16 @@ export function parseHost(host: string): SshTarget | string { if (close < 0) return 'a bracket is not closed'; address = rest.slice(1, close); const after = rest.slice(close + 1); - if (after !== '') { - if (!after.startsWith(':')) return 'only a port may follow the closing bracket'; - port = after.slice(1); - } - if (!/^[0-9a-fA-F:.]*:[0-9a-fA-F:.]*$/.test(address)) return 'the bracketed address is no IPv6 address'; + if (after !== '' && !after.startsWith(':')) return 'only a port may follow the closing bracket'; + if (after !== '') port = after.slice(1); + if (isIP(address) !== 6) return 'what the brackets hold is no IPv6 address'; } else if (rest.split(':').length > 2) { - if (!/^[0-9a-fA-F:.]+$/.test(rest)) return 'the address is no IPv6 address'; - } else if (rest.includes(':')) { + if (isIP(rest) !== 6) return 'it is no IPv6 address, which is bracketed where a port follows'; + } else { [address = '', port] = rest.split(':'); + const problem = addressProblem(address); + if (problem) return `the address ${problem}`; } - if (!rest.startsWith('[') && !address.includes(':') && !/^[A-Za-z0-9._-]+$/.test(address)) - return 'the address is empty or holds characters no name or address has'; if (port !== undefined && !(/^[0-9]+$/.test(port) && Number(port) >= 1 && Number(port) <= 65535)) return 'the port is not a number from 1 to 65535'; return { address, ...(user === undefined ? {} : { user }), ...(port === undefined ? {} : { port: Number(port) }) }; @@ -117,6 +134,8 @@ export interface Environment { secrets: Record; /** The names under `env` and under `secrets` whose value was refused: listed, with no value. */ refused: { env: string[]; secrets: string[] }; + /** The parts of the file whose value is unusable as a whole (`hostname` empty or no string, `env` or `secrets` no map): nothing is known of them, so no comparison reads them. */ + invalid: ('hostname' | 'env' | 'secrets')[]; /** The file could not be read as a map at all. */ unread: boolean; /** What makes the file unusable, one line each, each naming the file. */ @@ -143,6 +162,7 @@ async function readEnvironment(ctx: Context, dir: string, label: string): Promis env: {}, secrets: {}, refused: { env: [], secrets: [] }, + invalid: [], unread: false, problems: [], }; @@ -182,13 +202,17 @@ async function readEnvironment(ctx: Context, dir: string, label: string): Promis } if (doc.hostname !== undefined) { if (typeof doc.hostname === 'string' && doc.hostname !== '') environment.hostname = doc.hostname; - else problem('`hostname` is not a non-empty string'); + else { + problem('`hostname` is not a non-empty string'); + environment.invalid.push('hostname'); + } } for (const key of ['env', 'secrets'] as const) { const map = doc[key]; if (map === undefined || map === null) continue; if (!isMapping(map)) { problem(`\`${key}\` is not a map of names to values`); + environment.invalid.push(key); continue; } for (const [variable, value] of Object.entries(map)) { diff --git a/packages/lib/src/stacks.test.ts b/packages/lib/src/stacks.test.ts index bcf7cb21..5fba8bbd 100644 --- a/packages/lib/src/stacks.test.ts +++ b/packages/lib/src/stacks.test.ts @@ -692,6 +692,6 @@ test('a compose file whose aliases form a cycle is a bad compose file, which com stack: { 'compose.yaml': 'x-a: &a\n self: *a\nservices:\n web:\n image: ghcr.io/acme/shop:${PLEXUS_TAG}\n' }, apps: { shop: dockerfile }, }); - assert.deepEqual(codes(repo), ['bad-compose']); - assert.match(repo.problems[0]?.message ?? '', /aliases form a cycle/); + assert.ok(codes(repo).includes('bad-compose')); + assert.match(repo.problems.find((p) => p.code === 'bad-compose')?.message ?? '', /aliases form a cycle/); }); diff --git a/packages/lib/src/stacks.ts b/packages/lib/src/stacks.ts index 37acf050..f00d0b3f 100644 --- a/packages/lib/src/stacks.ts +++ b/packages/lib/src/stacks.ts @@ -158,9 +158,8 @@ export async function loadStacks(ctx: Context, rootGiven: string): Promise f.endsWith('.yml'))) problems.push({ code: 'bad-environment-file', - message: `${join(where, file)}: name it ${file.slice(0, -'.yml'.length)}.yaml`, + message: `${file}: name it ${file.slice(0, -'.yml'.length)}.yaml`, stack: name, }); const marker = entries.has(MARKER_FILE) ? await readMarker(ctx, join(dir, MARKER_FILE)) : undefined; From 0985106166efb27782dcedffad5a5af152a90179 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:22:44 +0100 Subject: [PATCH 35/91] compose.ts header: a cyclic alias is refused Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/compose.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/lib/src/compose.ts b/packages/lib/src/compose.ts index 49e6c402..d1954da7 100644 --- a/packages/lib/src/compose.ts +++ b/packages/lib/src/compose.ts @@ -3,7 +3,9 @@ // the deploy verb the images of its apps, and doctor runs the compose checks // of PLX-Stack over it. It reads what compose would read as far as plain YAML // goes, with anchors and merge keys resolved, and `${…}` interpolation left as -// written. A service that `extends` another service of the same file is read +// written. A +// document whose aliases form a cycle is a usage error, as compose refuses it, so +// that no walk of the document meets one. A service that `extends` another service of the same file is read // merged with it, through a chain of such services (`resolveExtends`); // services that extend each other in a cycle are an error naming them, as // compose refuses them. Not read: the files an `include` names, whose presence From d8a580dadd45834f4cfffb8043b524b1407bd461 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:23:33 +0100 Subject: [PATCH 36/91] test: the plexus_apps message says what the host no longer gets It names what stops (changes to values, secrets, port and route reach no host; a rotated secret re-creates nothing; a new record gets no directory) and what each deployment keeps until its repo holds its environment file. Red: the message says none of it. Co-Authored-By: Claude Opus 5.5 --- tests/platform-playbook.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh index a4b61a4c..a13cd344 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -229,7 +229,12 @@ EOF before=$(snapshot migrated /opt/stacks/shop-production /etc/caddy/apps.caddy) play migrated [ "$status" = 0 ] || fail "exit code $status" -grep -q '"msg": "plexus_apps is no longer read' "$work/out" || fail "no message that plexus_apps is no longer read" +message=$(sed -n 's/^ *"msg": "\(plexus_apps is no longer read.*\)"$/\1/p' "$work/out") +[ -n "$message" ] || fail "no message that plexus_apps is no longer read" +# What the host no longer gets from the records, and what it keeps. +for point in values secrets port route rotat re-creat 'new record' director 'keeps running' 'environment file'; do + grep -qi -- "$point" <<<"$message" || fail "the message does not say what becomes of '$point': $message" +done [ "$(snapshot migrated /opt/stacks/shop-production /etc/caddy/apps.caddy)" = "$before" ] || fail "a deployment's file or apps.caddy changed" [ -z "$(on migrated cat /var/log/docker-calls 2>/dev/null)" ] || fail "docker was run: $(on migrated cat /var/log/docker-calls)" [ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the deployment's route no longer answers" From 15cbc9aa2f7602b5dc1e5854b26a4b6498fa4778 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:24:26 +0100 Subject: [PATCH 37/91] The plexus_apps message says what the host no longer gets, and what it keeps The run still goes on: failing it would hold back the baseline and the lock-down roles on a host that carries deployments. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/playbooks/playbook.yml | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/ansible/platform/playbooks/playbook.yml b/ansible/platform/playbooks/playbook.yml index bf3590ac..2e85561c 100644 --- a/ansible/platform/playbooks/playbook.yml +++ b/ansible/platform/playbooks/playbook.yml @@ -56,10 +56,12 @@ when: plexus_apps | default([]) | length > 0 ansible.builtin.debug: msg: >- - plexus_apps is no longer read: the platform playbook lays out no environment and writes no .env, - .env.secret or route from it; the stack playbook does, from the stack's environment file. What earlier - versions wrote from it stays as it was, the routes in /etc/caddy/apps.caddy among it. Remove the records - once every environment on this host deploys from its environment file. + plexus_apps is no longer read, and the platform playbook writes nothing from it: a change to a record's + values, secrets, port or route reaches no host any more, a rotated secret re-creates no container, and a + new record gets no directory, so it cannot be deployed. Each deployment on this host keeps running, and + keeps deploying, with the .env, .env.secret and route it has, until its repo holds its environment file + and the stack playbook writes them from there. The routes earlier versions wrote stay in + /etc/caddy/apps.caddy until removed by hand; remove the records once no deployment needs them. tags: [always] roles: - { role: plexus.platform.deploy_user, tags: [deploy_user] } From 3d5f743f409954164cb3f7a22a4f4e365a392362 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:25:11 +0100 Subject: [PATCH 38/91] test: a run fails on a proxy configuration that is invalid on disk Two fragments serve one hostname and the root does not change: the run fails, and the failing task says what Caddy says. Red: the run exits 0. Co-Authored-By: Claude Opus 5.5 --- tests/platform-playbook.sh | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh index a13cd344..469b72d3 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -182,6 +182,19 @@ as plexus fresh sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does [[ $(get fresh preview.shop.example.com /) == *'Back in a minute'*' 503' ]] || fail "no maintenance page where nothing answers" echo "✓ $case" +case='a proxy configuration that is invalid on disk' +# Two fragments serve one hostname; the root Caddyfile does not change. +fragment fresh shop-twice.caddy 'http://shop.example.com { + import stack 20001 +}' +play fresh +[ "$status" != 0 ] || fail "exit code 0" +grep -q '"msg": "[^"]*ambiguous site definition: http://shop.example.com' "$work/out" || fail "the failing task does not say what Caddy says" +as plexus fresh rm /etc/caddy/stacks/shop-twice.caddy +play fresh +[ "$status" = 0 ] || fail "exit code $status once the configuration is valid again" +echo "✓ $case" + case='a host that carries deployments of an earlier version' host migrated # As the earlier platform playbook left it: the deployment's directory with its From 72240a14e706eeb72153af3c9dab64a2a4af9736 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:26:30 +0100 Subject: [PATCH 39/91] ingress validates the proxy's whole configuration in every run caddy validate over /etc/caddy/Caddyfile, fragments and apps.caddy included, in every run and in a dry run, changing nothing; the run fails with Caddy's error message where it is invalid. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/roles/ingress/tasks/main.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/ansible/platform/roles/ingress/tasks/main.yml b/ansible/platform/roles/ingress/tasks/main.yml index 3cc4f787..90ee47f3 100644 --- a/ansible/platform/roles/ingress/tasks/main.yml +++ b/ansible/platform/roles/ingress/tasks/main.yml @@ -80,3 +80,22 @@ mode: "0644" validate: caddy validate --config %s --adapter caddyfile notify: Reload caddy + +# The whole configuration as the proxy reads it on its next reload, the +# fragments and apps.caddy included, in every run and in a dry run too: the +# template above validates only a root that changes. It changes nothing. +- name: Validate the proxy's whole configuration + ansible.builtin.command: + cmd: caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile + register: ingress_validate + changed_when: false + failed_when: false + check_mode: false + +- name: Fail with what Caddy says of the configuration + when: ingress_validate.rc != 0 + ansible.builtin.fail: + msg: >- + the proxy's configuration on disk is invalid, and every reload fails until it is mended: + {{ ingress_validate.stderr_lines | select('search', '"level":"error"') | map('from_json') | map(attribute='msg') + | join('; ') or ingress_validate.stderr | default('caddy validate said nothing', true) }} From 9a11aa62fca4ec665e31e2f24dc272c38f4b7f85 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:27:32 +0100 Subject: [PATCH 40/91] test: an invalid sudo rule or root Caddyfile never lands, and apps.caddy is never written A deploy user's name that makes the rule invalid fails the run at the rule's task, refused by its validation; a root Caddyfile Caddy refuses fails at its task; the sudo rules and the root stay as they were, and the proxy reloads and serves. apps.caddy is written neither on a fresh host nor after it was deleted. Red: the run fails at the fragment directory before the rule is tried. Co-Authored-By: Claude Opus 5.5 --- tests/platform-playbook.sh | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh index 469b72d3..a43f35c3 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -104,11 +104,11 @@ platform: EOF } -# play [arguments]: one run of the platform layer on the host; its exit -# code in $status, its output in $work/out. +# play [arguments]: one run of the platform layer on the host, or of the +# roles $tags names; its exit code in $status, its output in $work/out. play() { status=0 - timeout 600 ansible-playbook -i "$work/$1.yml" --tags platform --skip-tags caddy "${@:2}" \ + timeout 600 ansible-playbook -i "$work/$1.yml" --tags "${tags:-platform}" --skip-tags caddy "${@:2}" \ plexus.platform.playbook "$work/out" 2>&1 || status=$? } @@ -138,6 +138,7 @@ play fresh ! grep -q '"msg": "plexus_apps is no longer read' "$work/out" || fail "a message about plexus_apps" [ "$(on fresh stat -c '%U:%G %a' /opt/stacks)" = 'plexus:plexus 750' ] || fail "/opt/stacks is not the deploy user's" as plexus fresh sh -c 'mkdir /opt/stacks/probe && rmdir /opt/stacks/probe' || fail "the deploy user cannot write /opt/stacks" +on fresh test ! -e /etc/caddy/apps.caddy || fail "apps.caddy was written" fragment fresh shop-staging.caddy 'http://shop.example.com { respond "from a fragment" }' @@ -195,6 +196,23 @@ play fresh [ "$status" = 0 ] || fail "exit code $status once the configuration is valid again" echo "✓ $case" +case='an invalid sudo rule or root configuration does not land' +before=$(snapshot fresh /etc/sudoers.d /etc/caddy/Caddyfile) +# failed : the run failed at the task of ingress named , which refused what it would have written. +failed() { + [ "$status" != 0 ] || fail "exit code 0" + grep -A2 "^TASK \[plexus.platform.ingress : $1" "$work/out" | grep -q 'failed to validate' || fail "'$1' did not refuse it" +} +tags=ingress play fresh -e '{"plexus_deploy_user": "ex ample"}' +failed 'Let the deploy user reload the proxy' +play fresh -e '{"ingress_trusted_proxies": ["not-a-cidr"]}' +failed 'Write the root Caddyfile' +[ "$(snapshot fresh /etc/sudoers.d /etc/caddy/Caddyfile)" = "$before" ] || fail "a sudo rule or the root Caddyfile changed" +on fresh visudo -c >/dev/null || fail "visudo -c finds an error in the host's sudo rules" +as plexus fresh sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload" +[ "$(get fresh shop.example.com /)" = 'shop staging 200' ] || fail "the route is no longer served" +echo "✓ $case" + case='a host that carries deployments of an earlier version' host migrated # As the earlier platform playbook left it: the deployment's directory with its @@ -283,6 +301,7 @@ on migrated rm /etc/caddy/apps.caddy as plexus migrated sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload once apps.caddy is gone" play migrated [ "$status" = 0 ] || fail "exit code $status" +on migrated test ! -e /etc/caddy/apps.caddy || fail "apps.caddy was written" as plexus migrated sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload after the platform playbook" [ "$(get migrated shop.example.com /)" = 'shop production, by its fragment 200' ] || fail "the route is not served" [ "$(get migrated staging.shop.example.com /)" = 'shop staging 200' ] || fail "the route is not served" From f37dd898b9ba9d5f8f72a472112cb04d129d5f8a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:27:54 +0100 Subject: [PATCH 41/91] Test: a version lands on the default branch origin says now, not on a stale record Co-Authored-By: Claude Sonnet 5.5 --- packages/dev/src/ship.integration.test.ts | 26 +++++++------- packages/lib/src/consumers.test.ts | 41 +++++++++++++---------- 2 files changed, 35 insertions(+), 32 deletions(-) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index 711c25c3..ab025479 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -1510,27 +1510,25 @@ test('update --recursive: a repo whose origin says no default branch is skipped, git(remote('acme-web'), 'update-ref', '-d', 'refs/heads/develop'); const { result, error, out } = await runRecursive({ yes: true }, { to: '0.2.0' }); assert.equal(error, undefined, out); - assert.match(out, /⚠ acme\/web: the default branch of origin cannot be determined.*set-head origin -a.* — skipped/); + assert.match( + out, + /⚠ acme\/web: origin's HEAD names no existing branch.*set the default branch on the forge.* — skipped/, + ); assert.equal(result?.skipped.length, 1); assert.deepEqual(result?.failed, []); assert.equal(result?.pulls.length, 1, 'the other repo takes the version'); }); -test('update --recursive: a repo whose checkout records a default branch that origin lost is skipped, with the reason', async () => { - fixture('no-branch'); +test('update --recursive: a clone made while develop was the default lands the version on the default branch origin has now', async () => { + fixture('stale-record'); git(join(WS, 'acme/web'), 'remote', 'set-head', 'origin', 'develop'); - git(remote('acme-web'), 'update-ref', '-d', 'refs/heads/develop'); + git(remote('acme-web'), 'branch', '--quiet', 'main', 'develop'); + git(remote('acme-web'), 'symbolic-ref', 'HEAD', 'refs/heads/main'); const { result, error, out } = await runRecursive({ yes: true }, { to: '0.2.0' }); assert.equal(error, undefined, out); - const reason = - 'origin has no branch `develop`, the default branch the version lands on; if the default branch changed on the forge, `git remote set-head origin -a` refreshes what the checkout records'; - assert.ok(has(out, `⚠ acme/web: ${reason} — skipped`), out); - assert.deepEqual(result?.skipped, [{ path: 'acme/web', reason }]); - assert.deepEqual(result?.failed, []); - assert.equal(result?.pulls.length, 1, 'the other repo takes the version'); - const alone = await runUpdate({ yes: true }, { repo: join(WS, 'acme/web'), to: '0.2.0' }); - assert.equal(alone.error, undefined, alone.out); - assert.deepEqual(alone.result?.skipped, [{ path: 'web', reason }]); + assert.deepEqual(result?.skipped, []); + assert.equal(pull('acme-web', '0.2.0', '.base'), 'main'); + assert.equal(git(remote('acme-web'), 'rev-list', '--count', 'main..plexus/0.2.0'), '1'); }); test('the confirmation aborts cleanly without a terminal', async () => { @@ -2768,7 +2766,7 @@ test('the preview reports a consumer without an origin, one whose origin cannot ); assert.ok(has(out, '⚠ acme/noorigin: no origin remote — not previewed'), out); assert.ok( - has(out, '⚠ acme/gone: the default branch of origin cannot be determined') && has(out, '— not previewed'), + has(out, '⚠ acme/gone: origin did not answer') && has(out, '— not previewed'), 'an origin that cannot be asked leaves no default branch to clone', ); assert.deepEqual(result?.failed, ['acme/legacy']); diff --git a/packages/lib/src/consumers.test.ts b/packages/lib/src/consumers.test.ts index 1f066c8c..c8b742d6 100644 --- a/packages/lib/src/consumers.test.ts +++ b/packages/lib/src/consumers.test.ts @@ -60,11 +60,14 @@ async function consumersWith( return findRepos(ctx, dir('/w', {}, repos)); } -test('a version lands on the default branch of origin that the checkout records, in an app repo and an operations repo alike, with no call to origin', async () => { +const says = (branch: string) => `ref: refs/heads/${branch}\tHEAD\n0123456789abcdef\tHEAD\n`; + +test('a version lands on the default branch origin says, in an app repo and an operations repo alike, whatever the checkout records', async () => { const calls: string[][] = []; const repos = await consumersWith((args) => { calls.push(args); - return args[0] === 'symbolic-ref' ? 'origin/trunk' : undefined; + if (args[0] === 'ls-remote') return says('trunk'); + return args[0] === 'symbolic-ref' ? 'origin/develop' : undefined; }); assert.deepEqual( repos.map((r) => [r.rel, r.branch, r.skipped]), @@ -72,30 +75,32 @@ test('a version lands on the default branch of origin that the checkout records, ['shop', 'trunk', undefined], ['platform', 'trunk', undefined], ], + 'a clone made while develop was the default does not land on develop', ); - assert.ok(!calls.some((c) => c[0] === 'ls-remote')); + assert.ok(!calls.some((c) => c[0] === 'symbolic-ref'), 'the checkout’s record is not read'); }); -test('a checkout that records no default branch asks origin for its HEAD', async () => { - const repos = await consumersWith((args) => - args[0] === 'ls-remote' ? 'ref: refs/heads/develop\tHEAD\n0123456789abcdef\tHEAD\n' : undefined, - ); - assert.deepEqual( - repos.map((r) => [r.branch, r.skipped]), - [ - ['develop', undefined], - ['develop', undefined], - ], +test('a package repo lands on its origin’s default branch too, and a branch name with a slash is read whole', async () => { + const repos = await consumersWith( + (args) => (args[0] === 'ls-remote' ? says('release/1') : undefined), + { config: { version: '0.2.0', templates: ['repo-turbo'], deviations: [], answers: { publishes_packages: true } } }, + ['shop'], ); + assert.deepEqual([repos[0]?.branch, repos[0]?.skipped], ['release/1', undefined]); }); -test('a repo whose default branch cannot be determined is skipped with why and what to do, never guessed', async () => { +test('an origin that does not answer skips the repo, saying so and what helps, and none is guessed', async () => { const repos = await consumersWith(() => undefined, {}, ['shop']); assert.equal(repos[0]?.branch, 'checked-out', 'the branch it is on is no answer'); - assert.match(repos[0]?.skipped ?? '', /default branch of origin cannot be determined/); - assert.match(repos[0]?.skipped ?? '', /git remote set-head origin -a/); - const odd = await consumersWith((args) => (args[0] === 'ls-remote' ? 'no symref here\n' : undefined), {}, ['shop']); - assert.match(odd[0]?.skipped ?? '', /cannot be determined/); + assert.match(repos[0]?.skipped ?? '', /origin did not answer/); + assert.match(repos[0]?.skipped ?? '', /check the access/); + assert.doesNotMatch(repos[0]?.skipped ?? '', /set-head/); +}); + +test('an origin whose HEAD names no existing branch skips the repo, saying so and what helps', async () => { + const repos = await consumersWith((args) => (args[0] === 'ls-remote' ? '' : undefined), {}, ['shop']); + assert.match(repos[0]?.skipped ?? '', /HEAD names no existing branch/); + assert.match(repos[0]?.skipped ?? '', /set the default branch on the forge/); }); test('a repo that has not crossed over is taken on the branch its checkout is on, and origin is not asked', async () => { From 3f0fba7e550520a90fe2f0f576ea0f851668fb59 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:29:14 +0100 Subject: [PATCH 42/91] plx update asks origin for its default branch and reads no record of it Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/consumers.ts | 50 +++++++++++++++++------------------ packages/lib/src/update.ts | 6 ++--- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/packages/lib/src/consumers.ts b/packages/lib/src/consumers.ts index 3bbb3894..1b32789f 100644 --- a/packages/lib/src/consumers.ts +++ b/packages/lib/src/consumers.ts @@ -4,14 +4,12 @@ // branch of its origin, whatever kind of repo it is. A repo without a marker, // or that has not crossed over, is taken on the branch its checkout is on. // -// The default branch is read from `origin/HEAD` of the checkout, which costs -// no call, and failing that from origin's own HEAD (`git ls-remote --symref`), -// which works in a fresh CI checkout, where git records no `origin/HEAD`, and -// with any forge. The checkout's record goes stale when the default branch -// changes on the forge, until `git remote set-head origin -a` is run; `update` -// notices when the recorded branch is gone from origin and skips the repo, -// saying so. A repo whose default branch neither tells is skipped, never -// guessed from the branch it is on or from a name. +// The default branch is what origin says its HEAD is, asked with +// `git ls-remote --symref origin HEAD`: one call per repo, which works in a +// fresh CI checkout and with any forge, and never reads what the checkout +// remembers of origin. A repo whose origin does not answer, or whose HEAD names +// no existing branch, is skipped, never guessed from the branch it is on or +// from a name. // // `findRepos` finds them for `plx update`: every git repo whose root marker // names a version or lists templates, and every one that carries a marker and @@ -19,12 +17,12 @@ // the crossover runbook. import { relative } from 'node:path'; import type { Context } from './context.ts'; -import { type Directory, hasMarker, isOperations } from './model.ts'; +import { type Directory, hasMarker } from './model.ts'; export interface Consumer { path: string; rel: string; - /** The branch the version lands on: origin's default branch, or the checkout's own when the marker names none. */ + /** The branch the version lands on: origin's default branch, or the checkout's own for a repo that has not crossed over. */ branch: string; /** The URL of `origin`, which the scratch clone is made from. */ origin?: string; @@ -43,17 +41,20 @@ const consumerOf = (root: Directory, dir: Directory): Consumer & { onDefault: bo onDefault: landsOnDefault(dir), }); -/** What `git remote set-head origin -a` does, to be told to whoever is skipped. */ -const SET_HEAD = '`git remote set-head origin -a` records it'; - -/** The default branch of origin: as the checkout records it, else as origin says; undefined when neither does. */ -async function defaultBranch(ctx: Context, cwd: string): Promise { - const recorded = ( - await ctx.read('git', ['symbolic-ref', '--short', '-q', 'refs/remotes/origin/HEAD'], { cwd }).catch(() => '') - ).trim(); - if (recorded.startsWith('origin/')) return recorded.slice('origin/'.length); - const said = await ctx.read('git', ['ls-remote', '--symref', 'origin', 'HEAD'], { cwd }).catch(() => ''); - return /^ref: refs\/heads\/(\S+)\s+HEAD$/m.exec(said)?.[1]; +/** The default branch origin says, or why it cannot be told. */ +async function defaultBranch(ctx: Context, cwd: string): Promise<{ branch: string } | { why: string }> { + let said: string; + try { + said = await ctx.read('git', ['ls-remote', '--symref', 'origin', 'HEAD'], { cwd }); + } catch { + return { why: 'origin did not answer when asked for its default branch; check the access to it, then re-run' }; + } + const branch = /^ref: refs\/heads\/(\S+)\s+HEAD$/m.exec(said)?.[1]; + return branch + ? { branch } + : { + why: "origin's HEAD names no existing branch, so it has no default branch; set the default branch on the forge, then re-run", + }; } /** Each consumer's origin, which the scratch clone is made from, and the default branch it lands on; one without either is skipped. */ @@ -65,10 +66,9 @@ async function withOrigins(ctx: Context, consumers: (Consumer & { onDefault: boo else { c.origin = origin; if (onDefault) { - const branch = await defaultBranch(ctx, c.path); - if (branch) c.branch = branch; - else - c.skipped = `the default branch of origin cannot be determined: the checkout records none and origin does not say (is it reachable?); ${SET_HEAD}, or fix the access, then re-run`; + const answer = await defaultBranch(ctx, c.path); + if ('branch' in answer) c.branch = answer.branch; + else c.skipped = answer.why; } } found.push(c); diff --git a/packages/lib/src/update.ts b/packages/lib/src/update.ts index ebf803ea..bd9fc053 100644 --- a/packages/lib/src/update.ts +++ b/packages/lib/src/update.ts @@ -18,8 +18,8 @@ // and their dates are what the interval is measured against. // // The repo is judged by what origin has on the branch the version lands on, its -// default branch (consumers.ts), never by the checkout, which may be behind it or on a branch -// of its own. Its markers there are its configuration (sites.ts): the root +// default branch (consumers.ts), never by the checkout, which may be behind it +// or on a branch of its own. Its markers there are its configuration (sites.ts): the root // marker's `version` is the version the repo is on, and refusing a downgrade, // the interval and readiness all read it. A repo that still tracks a copier // answers file there has not crossed over to the markers, and is refused with @@ -225,7 +225,7 @@ export async function update(ctx: Context, options: UpdateOptions, known?: Known // Without the branch the version lands on there is nothing to take it on. if ((await onOrigin(ctx, repo, consumer.branch)) === false) { - const reason = `origin has no branch \`${consumer.branch}\`, the default branch the version lands on; if the default branch changed on the forge, \`git remote set-head origin -a\` refreshes what the checkout records`; + const reason = `origin has no branch \`${consumer.branch}\`, the one the version lands on`; ctx.say(`⚠ ${name}: ${reason} — skipped`); return { repo: name, version: newest, kind: 'skipped', reason }; } From e9dd4ce371f6cd98c707e51f260dd07dc7dbc9e2 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:30:28 +0100 Subject: [PATCH 43/91] ingress writes the reload rule first; its header states once what a fragment is and can do The rule's task runs before the fragment directory, so a rule its validation refuses fails the run there. The header now says what whoever writes a fragment can do to the proxy, and that the refusal of /healthz reaches a route only through the snippet its fragment imports. The fragment's shape and the reload rule are stated in the header alone; the defaults and the root template point there. Co-Authored-By: Claude Opus 5.5 --- .../platform/roles/ingress/defaults/main.yml | 5 +- ansible/platform/roles/ingress/tasks/main.yml | 48 +++++++++++-------- .../roles/ingress/templates/root.Caddyfile.j2 | 9 ++-- 3 files changed, 34 insertions(+), 28 deletions(-) diff --git a/ansible/platform/roles/ingress/defaults/main.yml b/ansible/platform/roles/ingress/defaults/main.yml index 26821a70..f9a46ae4 100644 --- a/ansible/platform/roles/ingress/defaults/main.yml +++ b/ansible/platform/roles/ingress/defaults/main.yml @@ -1,7 +1,6 @@ --- -# Where the stacks' routes live: one file per environment that has a hostname, -# -.caddy, written by the stack playbook as the deploy -# user, who owns the directory; the root Caddyfile imports every *.caddy in it. +# The directory of route fragments, owned by the deploy user; what a fragment +# is, and who writes it, is the header of tasks/main.yml. ingress_fragments_dir: /etc/caddy/stacks # The maintenance page a stack's route serves while the stack does not diff --git a/ansible/platform/roles/ingress/tasks/main.yml b/ansible/platform/roles/ingress/tasks/main.yml index 90ee47f3..b834f003 100644 --- a/ansible/platform/roles/ingress/tasks/main.yml +++ b/ansible/platform/roles/ingress/tasks/main.yml @@ -17,12 +17,24 @@ # maintenance page, the same for every stack. # - The reload rule, /etc/sudoers.d/reload-caddy, exactly # ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy -# run as `sudo -n /usr/bin/systemctl reload caddy`. The reload reads the -# whole configuration again; where it is invalid (a fragment that does not -# parse, a hostname that two files serve), the reload fails, the proxy goes -# on serving what it served, and every later reload, of any stack's, and -# this role's validation fail too until the file is mended or removed. The -# deploy user can run `caddy validate --config /etc/caddy/Caddyfile` first. +# run as `sudo -n /usr/bin/systemctl reload caddy`, a command of its own: +# Ansible's become cannot use the rule, since it wraps every command in a +# shell. The reload reads the whole configuration again; where it is +# invalid (a fragment that does not parse, a hostname that two files +# serve), the reload fails, the proxy goes on serving what it served, and +# every later reload, of any stack's, and this role's validation fail too +# until the file is mended or removed. The deploy user can run +# `caddy validate --config /etc/caddy/Caddyfile` first. +# +# What a fragment can do: whoever writes one configures the proxy whole, as +# the proxy's user. A fragment can serve any file that user reads, listen on +# another port, and reach the proxy's admin API; a global block in it, such +# as `{ admin off }`, is taken by the reload and makes every later reload fail +# until root restarts the proxy. The refusal of /healthz reaches a route only +# because its fragment imports the snippet `stack`. That is the deployer's +# trust by another path, since a key that deploys to a host is root on it +# through Docker anyway; the stack playbook writes fragments of the one shape +# above and nothing else. # # While a host migrates, the routes of earlier versions and the fragments # coexist. Earlier versions rendered every route of the host from plexus_apps @@ -42,19 +54,8 @@ path: /etc/caddy/apps.caddy register: ingress_earlier_routes -# Not recursive: the fragments in it are the stack playbook's. -- name: Give the deploy user the directory of route fragments - ansible.builtin.file: - path: "{{ ingress_fragments_dir }}" - state: directory - owner: "{{ plexus_deploy_user }}" - group: "{{ plexus_deploy_user }}" - mode: "0755" - -# The deploy user's one privilege: one command, its arguments matched exactly, -# as root. Ansible's become cannot use it (it wraps every command in a shell); -# the stack playbook runs `sudo -n /usr/bin/systemctl reload caddy` as a -# command of its own. +# The deploy user's one privilege, the reload rule of the header. Before the +# fragment directory: a rule its validation refuses fails the run here. - name: Let the deploy user reload the proxy, and do nothing else as root ansible.builtin.copy: dest: /etc/sudoers.d/reload-caddy @@ -66,6 +67,15 @@ mode: "0440" validate: visudo -cf %s +# Not recursive: the fragments in it are the stack playbook's. +- name: Give the deploy user the directory of route fragments + ansible.builtin.file: + path: "{{ ingress_fragments_dir }}" + state: directory + owner: "{{ plexus_deploy_user }}" + group: "{{ plexus_deploy_user }}" + mode: "0755" + - name: Load Cloudflare's ranges ansible.builtin.include_vars: file: cloudflare.yml diff --git a/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 b/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 index 0f332d6c..ade5709f 100644 --- a/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 +++ b/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 @@ -24,11 +24,8 @@ } {% endif %} -# What every stack's route does but its hostname and port, stated here once. A -# route fragment is exactly -# { -# import stack -# } +# What every stack's route does but its hostname and port, imported by each +# route fragment (its shape: the header of the ingress role's tasks). # /healthz is refused from outside, for every stack: defence in depth for # stacks whose healthcheck answers on that conventional path, which publicly # would tell anyone whether their dependencies are up. The deploy does not @@ -69,5 +66,5 @@ import /etc/caddy/apps*.caddy {% endif %} -# The stacks' routes, one fragment per environment, written by the stack playbook. +# The stacks' route fragments. import {{ ingress_fragments_dir }}/*.caddy From 716ad593fb9c6f391b1aaacfd1a4df70dc208d61 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:31:56 +0100 Subject: [PATCH 44/91] The deploy root is /opt/stacks, no variable, on the platform's side It is the path PLX-Stack/HostDirectory names; plexus_deploy_root, which the operations template still renders, is no longer read. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/roles/deploy_user/defaults/main.yml | 12 ++++++------ ansible/platform/roles/deploy_user/tasks/main.yml | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/ansible/platform/roles/deploy_user/defaults/main.yml b/ansible/platform/roles/deploy_user/defaults/main.yml index 90879864..250cc6a4 100644 --- a/ansible/platform/roles/deploy_user/defaults/main.yml +++ b/ansible/platform/roles/deploy_user/defaults/main.yml @@ -1,13 +1,13 @@ --- # The unprivileged user that owns the deploy root and as which the stack # playbook deploys over SSH; the role creates both, and changes nothing below -# the root. The plexus_ variables are shared with other roles -# (plexus.host.docker adds the user to the docker group), so they keep that -# prefix and have no default here; set them in the operations repo's group -# variables: +# the root. The deploy root is /opt/stacks and no variable: it is the path the +# stack contract names for every environment (PLX-Stack/HostDirectory). +# +# The plexus_ variables are shared with other roles (plexus.host.docker adds +# the user to the docker group), so they keep that prefix and have no default +# here; set them in the operations repo's group variables: # plexus_deploy_user the user's name -# plexus_deploy_root the directory the user owns, under which each -# environment of a stack has its own; unset: /opt/stacks # plexus_deploy_pubkey the public key the deployer connects with; unset or # empty: no key is authorized # plexus_ghcr_user the registry login the user pulls the stacks' images diff --git a/ansible/platform/roles/deploy_user/tasks/main.yml b/ansible/platform/roles/deploy_user/tasks/main.yml index 0f878e8d..7b0af778 100644 --- a/ansible/platform/roles/deploy_user/tasks/main.yml +++ b/ansible/platform/roles/deploy_user/tasks/main.yml @@ -10,7 +10,7 @@ # Not recursive: what lies below is the stack playbook's. - name: Give the deploy user the deploy root ansible.builtin.file: - path: "{{ plexus_deploy_root | default('/opt/stacks') }}" + path: /opt/stacks state: directory owner: "{{ plexus_deploy_user }}" group: "{{ plexus_deploy_user }}" From 1dedaacdef40ae019ea2f02bd9a22a0abf43f246 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:52:00 +0100 Subject: [PATCH 45/91] test: a dry run on a fresh host passes before the proxy is installed The first run on a fresh host, under --check, with no deploy user and no caddy binary yet. Red: the validation of the whole configuration fails, saying caddy validate said nothing. Co-Authored-By: Claude Opus 5.5 --- tests/platform-playbook.sh | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh index a43f35c3..8b535226 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -131,8 +131,16 @@ snapshot() { # fragment : a route fragment, written by the deploy user as the stack playbook writes one. fragment() { printf '%s\n' "$3" | docker exec -i -u plexus "$run-$1" sh -c "cat >/etc/caddy/stacks/$2"; } -case='a fresh host' +case='a dry run on a fresh host, before the proxy is installed' host fresh +# The caddy role, which installs the binary, changes nothing in a dry run. +on fresh mv /usr/bin/caddy /usr/bin/caddy.away +play fresh --check +[ "$status" = 0 ] || fail "exit code $status" +on fresh mv /usr/bin/caddy.away /usr/bin/caddy +echo "✓ $case" + +case='a fresh host' play fresh [ "$status" = 0 ] || fail "exit code $status" ! grep -q '"msg": "plexus_apps is no longer read' "$work/out" || fail "a message about plexus_apps" From 1f4e1592e28027d83d11ff32eda66a80d9c79ef1 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:53:31 +0100 Subject: [PATCH 46/91] ingress validates the whole configuration only where the proxy's binary is there A dry run on a fresh host has none yet, since the caddy role installs it; where it is there, the validation runs as before. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/roles/ingress/tasks/main.yml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/ansible/platform/roles/ingress/tasks/main.yml b/ansible/platform/roles/ingress/tasks/main.yml index b834f003..d5afe5c8 100644 --- a/ansible/platform/roles/ingress/tasks/main.yml +++ b/ansible/platform/roles/ingress/tasks/main.yml @@ -91,10 +91,17 @@ validate: caddy validate --config %s --adapter caddyfile notify: Reload caddy +# A dry run on a fresh host has no binary yet: the caddy role installs it. +- name: Look for the proxy's binary + ansible.builtin.stat: + path: /usr/bin/caddy + register: ingress_caddy + # The whole configuration as the proxy reads it on its next reload, the # fragments and apps.caddy included, in every run and in a dry run too: the # template above validates only a root that changes. It changes nothing. - name: Validate the proxy's whole configuration + when: ingress_caddy.stat.exists ansible.builtin.command: cmd: caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile register: ingress_validate @@ -103,7 +110,7 @@ check_mode: false - name: Fail with what Caddy says of the configuration - when: ingress_validate.rc != 0 + when: ingress_validate is not skipped and ingress_validate.rc != 0 ansible.builtin.fail: msg: >- the proxy's configuration on disk is invalid, and every reload fails until it is mended: From e6f3ead5529d38f53254f6b141e3521c13de315e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:54:21 +0100 Subject: [PATCH 47/91] test: an invalid proxy configuration does not keep a host from being locked down On a host whose configuration is invalid on disk, with the root unchanged and with a root that would change, the run fails with what Caddy says, the lock-down play still runs on the host, and the root is not replaced. Red: the failure in ingress drops the host from the lock-down play. Co-Authored-By: Claude Opus 5.5 --- tests/platform-playbook.sh | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh index 8b535226..fe3dbbaf 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -196,9 +196,23 @@ case='a proxy configuration that is invalid on disk' fragment fresh shop-twice.caddy 'http://shop.example.com { import stack 20001 }' +# refused: the run failed with what Caddy says, and the play after the +# platform's, the lock-down, still ran on the host. Of that play the container +# runs only its facts (the test runs the platform layer alone), which show +# that the host was not dropped from it. +refused() { + [ "$status" != 0 ] || fail "exit code 0" + grep -q '"msg": "[^"]*ambiguous site definition: http://shop.example.com' "$work/out" || fail "the run does not say what Caddy says" + sed -n '/^PLAY \[Lock down the platform hosts\]/,/^PLAY /p' "$work/out" | grep -q '^ok: \[fresh\]' || + fail "the lock-down play did not run on the host" +} play fresh -[ "$status" != 0 ] || fail "exit code 0" -grep -q '"msg": "[^"]*ambiguous site definition: http://shop.example.com' "$work/out" || fail "the failing task does not say what Caddy says" +refused +# The same where the root changes: its own validation reads the fragments too. +root=$(on fresh sha256sum /etc/caddy/Caddyfile) +play fresh -e ingress_maintenance_title=Gone +refused +[ "$(on fresh sha256sum /etc/caddy/Caddyfile)" = "$root" ] || fail "the root Caddyfile was replaced" as plexus fresh rm /etc/caddy/stacks/shop-twice.caddy play fresh [ "$status" = 0 ] || fail "exit code $status once the configuration is valid again" From 135455a6c09d029fbb3f950f5a09940f02417006 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:55:51 +0100 Subject: [PATCH 48/91] findRepos names every reason a repo is skipped Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/consumers.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/lib/src/consumers.ts b/packages/lib/src/consumers.ts index 1b32789f..6bfd9a8a 100644 --- a/packages/lib/src/consumers.ts +++ b/packages/lib/src/consumers.ts @@ -80,7 +80,8 @@ async function withOrigins(ctx: Context, consumers: (Consumer & { onDefault: boo * The repos under a scanned workspace (`overview` with git facets) that take a * version, in tree order: each git repo whose root marker names a version or * lists templates, or which carries a marker and tracks an answers file at its - * root. A repo without an origin is skipped. + * root. A repo without an origin, or whose origin does not say a default + * branch, is skipped. */ export async function findRepos(ctx: Context, root: Directory): Promise { const found: (Consumer & { onDefault: boolean })[] = []; From 795c0ad4dda3b2c019d848c3e1958f7a6ca3dddc Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:56:31 +0100 Subject: [PATCH 49/91] A proxy configuration Caddy refuses fails the host after the lock-down ingress records what Caddy says, of the root that would replace the one in place or of the whole configuration on disk, in ingress_invalid; the platform playbook's last play fails the host with it, after firewall and sshd have run. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/playbooks/playbook.yml | 17 ++++- ansible/platform/roles/ingress/tasks/main.yml | 64 +++++++++++-------- 2 files changed, 52 insertions(+), 29 deletions(-) diff --git a/ansible/platform/playbooks/playbook.yml b/ansible/platform/playbooks/playbook.yml index 2e85561c..72919ec5 100644 --- a/ansible/platform/playbooks/playbook.yml +++ b/ansible/platform/playbooks/playbook.yml @@ -16,7 +16,8 @@ # needs. It starts, re-creates and removes no container, changes nothing below # the deploy root, and writes no route. `plexus_apps`, the records of earlier # versions, is not read; a host that still sets records in it is told so, and -# the run goes on. +# the run goes on. A proxy configuration Caddy refuses fails the host in the +# last play, after the lock-down roles have run. # # A fresh host is reached as root once (`-u root`), which creates the admins; # every later run connects as an admin, and the first of those closes root @@ -80,3 +81,17 @@ roles: - { role: plexus.host.firewall, tags: [firewall] } # after the roles that open ports in it - { role: plexus.host.sshd, tags: [sshd] } # last: closes root logins once an admin has logged in + +# The proxy's configuration Caddy refused, which the ingress role records: the +# host fails here, after the lock-down roles, so that a route someone broke +# never keeps a host from its firewall and sshd settings. Tagged `platform` +# and `ingress`, so that `--tags ingress` reports it too. +- name: Report a proxy configuration Caddy refuses + hosts: platform + gather_facts: false + tags: [platform, ingress] + tasks: + - name: Fail the host whose proxy configuration Caddy refuses + when: ingress_invalid is defined + ansible.builtin.fail: + msg: "the proxy's configuration is invalid, and every reload fails until it is mended: {{ ingress_invalid }}" diff --git a/ansible/platform/roles/ingress/tasks/main.yml b/ansible/platform/roles/ingress/tasks/main.yml index d5afe5c8..b229b950 100644 --- a/ansible/platform/roles/ingress/tasks/main.yml +++ b/ansible/platform/roles/ingress/tasks/main.yml @@ -81,38 +81,46 @@ file: cloudflare.yml when: ingress_trusted_proxies == 'cloudflare' -# Validated as a whole before it replaces the one in place, with every file it -# imports: their paths are absolute, so they resolve from the copy too. -- name: Write the root Caddyfile - ansible.builtin.template: - src: root.Caddyfile.j2 - dest: /etc/caddy/Caddyfile - mode: "0644" - validate: caddy validate --config %s --adapter caddyfile - notify: Reload caddy - # A dry run on a fresh host has no binary yet: the caddy role installs it. - name: Look for the proxy's binary ansible.builtin.stat: path: /usr/bin/caddy register: ingress_caddy -# The whole configuration as the proxy reads it on its next reload, the -# fragments and apps.caddy included, in every run and in a dry run too: the -# template above validates only a root that changes. It changes nothing. -- name: Validate the proxy's whole configuration - when: ingress_caddy.stat.exists - ansible.builtin.command: - cmd: caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile - register: ingress_validate - changed_when: false - failed_when: false - check_mode: false +# A configuration Caddy refuses, the root that would replace the one in place +# or the whole on disk, is recorded in ingress_invalid and fails the host only +# in the last play of the platform playbook, after the lock-down roles: a +# route someone broke never keeps a host from its firewall and sshd settings. +# A playbook that uses this role without that play raises ingress_invalid +# itself. +- name: Write and validate the proxy's configuration + block: + # Validated as a whole before it replaces the one in place, with every + # file it imports: their paths are absolute, so they resolve from the + # copy too. + - name: Write the root Caddyfile + ansible.builtin.template: + src: root.Caddyfile.j2 + dest: /etc/caddy/Caddyfile + mode: "0644" + validate: caddy validate --config %s --adapter caddyfile + notify: Reload caddy + + # The whole configuration as the proxy reads it on its next reload, the + # fragments and apps.caddy included, in every run and in a dry run too: + # the template validates only a root that changes. It changes nothing. + - name: Validate the proxy's whole configuration + when: ingress_caddy.stat.exists + ansible.builtin.command: + cmd: caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile + changed_when: false + check_mode: false -- name: Fail with what Caddy says of the configuration - when: ingress_validate is not skipped and ingress_validate.rc != 0 - ansible.builtin.fail: - msg: >- - the proxy's configuration on disk is invalid, and every reload fails until it is mended: - {{ ingress_validate.stderr_lines | select('search', '"level":"error"') | map('from_json') | map(attribute='msg') - | join('; ') or ingress_validate.stderr | default('caddy validate said nothing', true) }} + rescue: + - name: Record what Caddy says of the configuration + ansible.builtin.set_fact: + ingress_invalid: >- + '{{ ansible_failed_task.name }}' failed: + {{ (ansible_failed_result.stderr | default('')).splitlines() | select('search', '"level":"error"') + | map('from_json') | map(attribute='msg') | join('; ') + or ansible_failed_result.msg | default('no message', true) }} From f7c96c0c9577933c4dce7dd601005b55270e9caf Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:57:59 +0100 Subject: [PATCH 50/91] test: a deploy root set to another path is named, and the run goes on plexus_deploy_root=/srv/stacks: the run says the variable is no longer read, that the path is /opt/stacks on every host, and that a deployment under /srv/stacks is not seen by the stack playbook; /srv/stacks is not created. /opt/stacks, the value the template renders, gets no message. The fixture of the earlier version no longer sets the variable, and the plexus_apps message is held to words of each of its points. Red: there is no message. Co-Authored-By: Claude Opus 5.5 --- tests/platform-playbook.sh | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh index fe3dbbaf..5f758d3e 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -235,6 +235,21 @@ as plexus fresh sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does [ "$(get fresh shop.example.com /)" = 'shop staging 200' ] || fail "the route is no longer served" echo "✓ $case" +case='a deploy root set to another path' +play fresh -e plexus_deploy_root=/srv/stacks +[ "$status" = 0 ] || fail "exit code $status" +message=$(sed -n 's/^ *"msg": "\(plexus_deploy_root is no longer read.*\)"$/\1/p' "$work/out") +[ -n "$message" ] || fail "no message that plexus_deploy_root is no longer read" +for point in '/opt/stacks on every host' 'under /srv/stacks is not seen by the stack playbook'; do + grep -qF -- "$point" <<<"$message" || fail "the message does not say: $point" +done +on fresh test ! -e /srv/stacks || fail "/srv/stacks was created" +# The value the operations template renders. +play fresh -e plexus_deploy_root=/opt/stacks +[ "$status" = 0 ] || fail "exit code $status" +! grep -q '"msg": "plexus_deploy_root is no longer read' "$work/out" || fail "a message for /opt/stacks" +echo "✓ $case" + case='a host that carries deployments of an earlier version' host migrated # As the earlier platform playbook left it: the deployment's directory with its @@ -263,11 +278,10 @@ docker cp -q "$work/apps.caddy" "$run-migrated:/etc/caddy/apps.caddy" on migrated sh -c 'printf "# Managed by Ansible (plexus.platform.ingress).\nimport apps.caddy\n" >/etc/caddy/Caddyfile && systemctl restart caddy' backend migrated 3001 'shop production' [ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the fixture's route does not answer" -# The group's variables as the operations template renders them, and the -# records the earlier version read, with a value that differs from the .env in -# place and a secret: a run that still read them would rewrite both. +# Group variables the operations template renders, and the records the earlier +# version read, with a value that differs from the .env in place and a secret: +# a run that still read them would rewrite both. cat >>"$work/migrated.yml" <<'EOF' - plexus_deploy_root: /opt/stacks plexus_up: true plexus_ghcr_user: "" plexus_ghcr_token: "" @@ -284,9 +298,11 @@ play migrated [ "$status" = 0 ] || fail "exit code $status" message=$(sed -n 's/^ *"msg": "\(plexus_apps is no longer read.*\)"$/\1/p' "$work/out") [ -n "$message" ] || fail "no message that plexus_apps is no longer read" -# What the host no longer gets from the records, and what it keeps. -for point in values secrets port route rotat re-creat 'new record' director 'keeps running' 'environment file'; do - grep -qi -- "$point" <<<"$message" || fail "the message does not say what becomes of '$point': $message" +# What the host no longer gets from the records, and what it keeps: each point +# by words that only it has. +for point in 'values, secrets, port or route reaches no host' 'rotated secret re-creates no container' \ + 'new record gets no directory' 'keeps running, and keeps deploying'; do + grep -qF -- "$point" <<<"$message" || fail "the message does not say: $point" done [ "$(snapshot migrated /opt/stacks/shop-production /etc/caddy/apps.caddy)" = "$before" ] || fail "a deployment's file or apps.caddy changed" [ -z "$(on migrated cat /var/log/docker-calls 2>/dev/null)" ] || fail "docker was run: $(on migrated cat /var/log/docker-calls)" From 674533558a3bf8cfc44917bd6e28e2498c76db1b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 02:59:49 +0100 Subject: [PATCH 51/91] The platform playbook says where plexus_deploy_root names another path The deploy root is /opt/stacks on every host; a host whose variable says otherwise is told that the variable is no longer read and that a deployment under its path is not seen by the stack playbook, and the run goes on. /opt/stacks, which the template renders, gets no message. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/playbooks/playbook.yml | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/ansible/platform/playbooks/playbook.yml b/ansible/platform/playbooks/playbook.yml index 72919ec5..4a9bff1c 100644 --- a/ansible/platform/playbooks/playbook.yml +++ b/ansible/platform/playbooks/playbook.yml @@ -15,8 +15,9 @@ # the stack playbook (plexus.platform.stack) does everything one environment # needs. It starts, re-creates and removes no container, changes nothing below # the deploy root, and writes no route. `plexus_apps`, the records of earlier -# versions, is not read; a host that still sets records in it is told so, and -# the run goes on. A proxy configuration Caddy refuses fails the host in the +# versions, is not read, nor is plexus_deploy_root; a host that still sets +# records in the one or another path than /opt/stacks in the other is told so, +# and the run goes on. A proxy configuration Caddy refuses fails the host in the # last play, after the lock-down roles have run. # # A fresh host is reached as root once (`-u root`), which creates the admins; @@ -64,6 +65,14 @@ and the stack playbook writes them from there. The routes earlier versions wrote stay in /etc/caddy/apps.caddy until removed by hand; remove the records once no deployment needs them. tags: [always] + - name: Say that plexus_deploy_root is no longer read + when: plexus_deploy_root | default('/opt/stacks') != '/opt/stacks' + ansible.builtin.debug: + msg: >- + plexus_deploy_root is no longer read: the deploy root is /opt/stacks on every host, which the platform + playbook gives the deploy user, and the stack playbook works there alone. A deployment under + {{ plexus_deploy_root }} is not seen by the stack playbook and stays as it is; remove the variable. + tags: [always] roles: - { role: plexus.platform.deploy_user, tags: [deploy_user] } - { role: plexus.platform.caddy, tags: [caddy] } From de7c98dd782e35864ef121444a7f5700229244bf Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 03:27:36 +0100 Subject: [PATCH 52/91] Test: the newborn update fixtures' origins have the repo's branch as their default Co-Authored-By: Claude Sonnet 5.5 --- newborns/update-released.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/newborns/update-released.test.ts b/newborns/update-released.test.ts index d4ace612..1ac54767 100644 --- a/newborns/update-released.test.ts +++ b/newborns/update-released.test.ts @@ -188,7 +188,8 @@ async function repoAt( here, env, ); - await sh('git', ['init', '--bare', '--quiet', origin], here, env); + // The forge's default branch is the branch the repo is on, as a forge makes it when a first push creates one. + await sh('git', ['init', '--bare', '--quiet', '--initial-branch', branch as string, origin], here, env); await sh('git', ['checkout', '-q', '-B', branch as string], dir, env); await sh('git', ['remote', 'add', 'origin', origin], dir, env); await git(dir, 'add', '-A'); From c36294b97b869a888d3407bc9062a5ea53e320d9 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:03:01 +0100 Subject: [PATCH 53/91] The stack playbook's test deploys from an environment's file Every case hands the playbook an environment's file instead of a directory the platform laid out: the playbook creates the directory and writes .env from `env`, and .env.secret from `secrets` through a stand-in of the vault's CLI. New cases: values and secrets reach the containers byte for byte and no secret reaches the output, with -v or --diff; a changed value beside a rotated secret that breaks the healthcheck ends with the previous .env, .env.secret, compose.yaml and containers; a secret the vault does not hold; files the playbook cannot write; a dry run of a new environment. Co-Authored-By: Claude Opus 5.5 --- tests/stack-playbook.sh | 217 ++++++++++++++++++++++++++++++++-------- 1 file changed, 174 insertions(+), 43 deletions(-) diff --git a/tests/stack-playbook.sh b/tests/stack-playbook.sh index b5844a79..8e51c3b7 100755 --- a/tests/stack-playbook.sh +++ b/tests/stack-playbook.sh @@ -1,17 +1,31 @@ #!/usr/bin/env bash # The stack playbook (plexus.platform.stack) against the Docker daemon of this -# machine: ansible-playbook on localhost with a local connection, a scratch -# directory in place of /opt/stacks, and a stack of two images built here -# (web and worker, busybox with a line or two) and a service `migrate`, every -# image pinned by digest from a throwaway registry on 127.0.0.1. Each case -# runs the playbook as `plx deploy` would and reads its last line, the -# containers and the files in the environment's directory. +# machine, in two parts. The first runs ansible-playbook with a local +# connection, a scratch directory in place of /opt/stacks, and environments +# without a hostname, for a stack of two images built here (web and worker, +# busybox with a line or two) and a service `migrate`, every image pinned by +# digest from a throwaway registry on 127.0.0.1. The second runs it against a +# host the platform playbook prepared, for environments with a hostname: their +# ports, their routes and the proxy. Each case runs the playbook as `plx +# deploy` would, with an environment's file, and reads its last line, the +# containers and the files in the environment's directory. The vault's CLI is +# a stand-in on the PATH that reads $work/vault. +# +# The prepared host is a container of the image of host-image.sh, booted with +# systemd, in this machine's network, so that its proxy reaches the loopback +# ports the stack's containers publish here, and with this daemon's socket, +# through which the deploy user's Compose starts them. Its proxy listens on +# 127.0.0.1 alone, on ports of the run's own, and issues certificates from its +# own CA; the environments take their ports from ten free ports of the run's +# own. # # Run by `mise test` (its task test-ansible), on every push by the hook and # in CI: it tests the playbook beside its source and needs no build, which is # `test`'s and not `e2e`'s (§ 3 PLX-Repo). It needs a Docker daemon, and the # network once for busybox:1.37 and registry:2; where no daemon answers, or -# an image is neither here nor to be pulled, it says so and passes. +# an image is neither here nor to be pulled, it says so and passes. The second +# part needs what platform-playbook.sh needs, and the daemon's socket at +# /var/run/docker.sock; where it cannot run, it says so and passes. # Everything it creates is named plxstack-… (the registry's image # references carry 127.0.0.1:/ before it), publishes on 127.0.0.1 only, # and is removed when it ends, whether a case failed or not. @@ -35,9 +49,10 @@ done run=plxstack-$$ work=$(mktemp -d) stacks=$work/stacks +mkdir -p "$stacks" "$work/env" "$work/vault" "$work/bin" # Every container, network, volume and image of this run, the registry's -# among them, whatever happened. +# and the prepared host's among them, whatever happened. cleanup() { docker ps -a --format '{{.Names}}' | grep "^$run" | xargs -r docker rm -f -v >/dev/null || true docker network ls --format '{{.Name}}' | grep "^$run" | xargs -r docker network rm >/dev/null || true @@ -45,6 +60,7 @@ cleanup() { # By reference, never by id: a run beside this one may have built the same image. docker image ls --digests --format '{{.Repository}}:{{.Tag}} {{.Repository}}@{{.Digest}}' | grep "/$run-" | tr ' ' '\n' | grep -v '$' | xargs -r docker image rm >/dev/null 2>&1 || true + docker image rm "$run:host" >/dev/null 2>&1 || true rm -rf "$work" } trap cleanup EXIT @@ -56,6 +72,19 @@ fail() { exit 1 } +# The vault's CLI as the playbook calls it: `op read --no-newline op://` +# prints the file $work/vault/ as it is. +cat >"$work/bin/op" <<'EOF' +#!/bin/sh +[ "$1 $2" = 'read --no-newline' ] || { echo "op: the stand-in reads, with --no-newline, and does not $*" >&2; exit 2; } +[ -f "$VAULT/${3#op://}" ] || { echo "[ERROR] could not read secret '$3': no such item" >&2; exit 1; } +cat "$VAULT/${3#op://}" +EOF +chmod +x "$work/bin/op" +export VAULT=$work/vault PATH=$work/bin:$PATH +# secret : the value the vault holds at the pointer. +secret() { mkdir -p "$(dirname "$VAULT/${1#op://}")" && printf '%s' "$2" >"$VAULT/${1#op://}"; } + # The registry the images are pinned from, its storage an anonymous volume. docker run -d --rm --name "$run-registry" -p 127.0.0.1::5000 registry:2 >/dev/null port=$(docker port "$run-registry" 5000/tcp | head -1 | sed 's/.*://') @@ -81,10 +110,10 @@ worker=$(image worker:v1 "$worker_dockerfile") # compose [migrate's shell command]: the stack's rendered compose # file. migrate adds a line to /data/migrated in the shared volume; web turns # healthy once there is one, and never where its image says it is broken or -# its environment HEALTH=bad (it loads .env); worker has no healthcheck. -# $web_more and $migrate_more are lines added to the two services. Without -# them nothing orders migrate or puts it behind a profile, the shape that makes -# a plain `up --wait` fail. +# its environment HEALTH=bad (it loads .env and .env.secret); worker has no +# healthcheck and loads neither. $web_more and $migrate_more are lines added +# to the two services. Without them nothing orders migrate or puts it behind +# a profile, the shape that makes a plain `up --wait` fail. compose() { cat <: its directory and .env, as the platform playbook lays them out. +# environment […]: the environment's file, $work/env/.yaml, +# its host this machine, and the lines given after `host`. environment() { - mkdir -p "$stacks/$run-shop-$1" - printf 'COMPOSE_PROJECT_NAME=%s\n' "$run-shop-$1" >"$stacks/$run-shop-$1/.env" + { echo 'host: localhost'; printf '%s\n' "${@:2}"; } >"$work/env/$1.yaml" } # deploy [arguments]: one run of the playbook, for -# the stack $stack (default $run-shop); its exit code in $status, its last -# line in $line. +# the stack $stack (default $run-shop) and the environment's file $envfile +# (default $work/env/.yaml), on this machine; its exit code in +# $status, its last line in $line. deploy() { status=0 - ansible-playbook -i localhost, -c local -e ansible_python_interpreter=auto_silent \ - -e stack_name="${stack:-$run-shop}" -e stack_environment="$1" -e stack_compose_file="$2" -e stack_root="$stacks" \ - "${@:3}" plexus.platform.stack "$work/out" 2>&1 || status=$? + ansible-playbook -c local -e ansible_python_interpreter=auto_silent \ + -e stack_name="${stack:-$run-shop}" -e stack_environment_file="${envfile:-$work/env/$1.yaml}" -e stack_compose_file="$2" \ + -e stack_root="$stacks" "${@:3}" plexus.platform.stack "$work/out" 2>&1 || status=$? line=$(sed -n 's/^ *"msg": "\(.*\)"$/\1/p' "$work/out" | tail -1) } @@ -134,6 +167,8 @@ deploy() { container() { docker ps -q --filter "label=com.docker.compose.project=$run-shop-$1" --filter "label=com.docker.compose.service=$2"; } image_of() { docker inspect --format '{{.Config.Image}}' "$(container "$1" "$2")"; } health_of() { docker inspect --format '{{.State.Health.Status}}' "$(container "$1" "$2")"; } +# The value of a variable in the container of web in an environment, as the process sees it. +value_of() { docker exec "$(container "$1" web)" sh -c "printf %s \"\$$2\""; } # How often migrate has run in an environment, read from its volume. migrations() { docker run --rm --name "$run-probe" -v "$run-shop-$1_data:/data" busybox:1.37 sh -c 'cat /data/migrated 2>/dev/null' | wc -l @@ -145,6 +180,10 @@ compose "$web_v1" >"$work/v1.yaml" deploy staging "$work/v1.yaml" [ "$status" = 0 ] || fail "exit code $status" [ "$line" = "$run-shop-staging: deployed" ] || fail "last line: $line" +[ "$(stat -c %a "$stacks/$run-shop-staging")" = 750 ] || fail "the directory is not 0750" +[ "$(cat "$stacks/$run-shop-staging/.env")" = "COMPOSE_PROJECT_NAME=\"$run-shop-staging\"" ] || + fail ".env: $(cat "$stacks/$run-shop-staging/.env")" +[ ! -e "$stacks/$run-shop-staging/.env.secret" ] || fail ".env.secret was written for an environment without secrets" [ "$(image_of staging web)" = "$web_v1" ] || fail "web does not run $web_v1" [ "$(health_of staging web)" = healthy ] || fail "web is not healthy" [ "$(image_of staging worker)" = "$worker" ] || fail "worker does not run $worker" @@ -164,6 +203,7 @@ deploy staging "$work/v2.yaml" [ "$(container staging web)" != "$web_id" ] || fail "web was not re-created" [ "$(container staging worker)" = "$worker_id" ] || fail "worker was re-created" cmp -s "$work/v1.yaml" "$stacks/$run-shop-staging/compose.yaml.prev" || fail "compose.yaml.prev is not the file deployed before" +[ ! -e "$stacks/$run-shop-staging/.env.prev" ] || fail ".env.prev was written, though .env did not change" echo "✓ $case" case='a deploy whose healthcheck fails' @@ -207,6 +247,7 @@ deploy preview "$work/broken.yaml" [[ $line == "$run-shop-preview: failed: "*unhealthy* ]] || fail "last line: $line" [ -z "$(docker ps -q --filter "label=com.docker.compose.project=$run-shop-preview")" ] || fail "containers left running" [ ! -e "$stacks/$run-shop-preview/compose.yaml" ] || fail "compose.yaml left in place" +[ -f "$stacks/$run-shop-preview/.env" ] || fail ".env was removed" echo "✓ $case" case='a deploy in which nothing changed' @@ -214,20 +255,28 @@ web_id=$(container staging web) worker_id=$(container staging worker) deploy staging "$work/v2.yaml" [ "$status" = 0 ] || fail "exit code $status" [ "$line" = "$run-shop-staging: unchanged" ] || fail "last line: $line" -grep -q 'localhost *: ok=[0-9]* *changed=0 ' "$work/out" || fail "a task reported a change" +! grep -q 'changed=[1-9]' "$work/out" || fail "a task reported a change" [ "$(container staging web)" = "$web_id" ] || fail "web was re-created" [ "$(container staging worker)" = "$worker_id" ] || fail "worker was re-created" echo "✓ $case" -case='an environment without its directory, then without .env' -deploy qa "$work/v1.yaml" -[ "$status" != 0 ] || fail "exit code 0" -[[ $line == "$run-shop-qa: failed: "*"$stacks/$run-shop-qa is not there"* ]] || fail "last line: $line" -mkdir "$stacks/$run-shop-qa" -deploy qa "$work/v1.yaml" -[ "$status" != 0 ] || fail "exit code 0" -[[ $line == "$run-shop-qa: failed: "*"$stacks/$run-shop-qa/.env is not there"* ]] || fail "last line: $line" -[ ! -e "$stacks/$run-shop-qa/compose.yaml" ] || fail "compose.yaml was written" +case="an environment's file the playbook cannot write" +# Each refused before anything is written: no directory for qa. +for file in 'hostname: qa.example.com' 'host: -oProxyCommand=x' 'host: localhost +env: {PORT: 3000}' 'host: localhost +secrets: {TOKEN: plain}' 'host: localhost +hostname: "qa.example.com {"' 'host: localhost +env: {PLEXUS_LOOPBACK_PORT: "3000"}' 'host: localhost +env: {TOKEN: a} +secrets: {TOKEN: op://acme/shop/qa/token}' 'host: localhost +domain: qa.example.com' '- host: localhost'; do + printf '%s\n' "$file" >"$work/env/qa.yaml" + deploy qa "$work/v1.yaml" + [ "$status" != 0 ] || fail "$file: exit code 0" + [[ $line == "$run-shop-qa: failed: 'Check the environment's file' failed: $work/env/qa.yaml is not an environment"* ]] || + fail "$file: last line: $line" + [ ! -e "$stacks/$run-shop-qa" ] || fail "$file: the directory was laid out" +done echo "✓ $case" case='a dry run (--check)' @@ -243,6 +292,11 @@ cmp -s "$work/prev.yaml" "$stacks/$run-shop-staging/compose.yaml.prev" || fail " [ "$(container staging worker)" = "$worker_id" ] || fail "worker was re-created" ! sed -n '/Pull the images\]/,/^$/p; /Bring the stack up\]/,/^$/p' "$work/out" | grep -q '^\(ok\|changed\|included\):' || fail "a Compose task ran" +# A new environment: nothing laid out. +environment draft +deploy draft "$work/v1.yaml" --check --diff +[ "$line" = "$run-shop-draft: would deploy" ] || fail "a new environment: last line: $line" +[ ! -e "$stacks/$run-shop-draft" ] || fail "a new environment: the directory was laid out" echo "✓ $case" case='a stack whose only service is migrate' @@ -322,24 +376,96 @@ deploy staging "$work/no-worker.yaml" [ "$(container staging web)" = "$web_id" ] || fail "web was re-created" echo "✓ $case" -case='a change of .env alone' +case='a change of a value alone' web_id=$(container staging web) -printf 'GREETING=hello\n' >>"$stacks/$run-shop-staging/.env" +cp "$stacks/$run-shop-staging/.env" "$work/env-before" +environment staging 'env:' ' GREETING: hello' deploy staging "$work/no-worker.yaml" [ "$status" = 0 ] || fail "exit code $status" [ "$line" = "$run-shop-staging: deployed" ] || fail "last line: $line" [ "$(container staging web)" != "$web_id" ] || fail "web was not re-created" +[ "$(value_of staging GREETING)" = hello ] || fail "web does not see GREETING=hello" [ "$(health_of staging web)" = healthy ] || fail "web is not healthy" +cmp -s "$work/env-before" "$stacks/$run-shop-staging/.env.prev" || fail ".env.prev is not the .env deployed before" echo "✓ $case" -case='a deploy of the file in place that fails' -cp "$stacks/$run-shop-staging/compose.yaml.prev" "$work/prev.yaml" -printf 'HEALTH=bad\n' >>"$stacks/$run-shop-staging/.env" +case='values and secrets reach the containers as written, and no secret reaches the output' +# A value that a shell, Compose and Ansible would each read otherwise, and a +# secret of two lines, with a newline at its end, as a key in the vault has. +value='a $HOME ${GREETING} "q" '\''s'\'' back\slash #x {{ lookup('\''pipe'\'', '\''id'\'') }}' +password=$'pa$$ "w0rd" \\n\n2nd-line-of-the-secret\n' +secret op://acme/shop/staging/password "$password" +secret op://acme/shop/staging/token 'token-of-the-secret' +environment staging 'env:' ' GREETING: hello' " ODD: '${value//\'/\'\'}'" 'secrets:' \ + ' DB_PASSWORD: op://acme/shop/staging/password' ' API_TOKEN: op://acme/shop/staging/token' +leaks() { grep -c -e 2nd-line-of-the-secret -e token-of-the-secret -e 'w0rd' "$work/out" || true; } +deploy staging "$work/no-worker.yaml" -v +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-shop-staging: deployed" ] || fail "last line: $line" +[ "$(leaks)" = 0 ] || fail "a secret is in the output of a run with -v" +[ "$(value_of staging ODD)" = "$value" ] || fail "ODD is $(value_of staging ODD)" +[ "$(value_of staging DB_PASSWORD)" = "${password%$'\n'}" ] || fail "DB_PASSWORD is $(value_of staging DB_PASSWORD)" +docker exec "$(container staging web)" sh -c 'printf %s "$DB_PASSWORD"' | cmp -s - "$VAULT/acme/shop/staging/password" || + fail "DB_PASSWORD is not the vault's value to its last byte" +[ "$(stat -c %a "$stacks/$run-shop-staging/.env.secret")" = 600 ] || fail ".env.secret is not 0600" +! grep -q -e w0rd -e token-of-the-secret "$stacks/$run-shop-staging/.env" || fail "a secret is in .env" +secret op://acme/shop/staging/token 'token-of-the-secret, rotated' +deploy staging "$work/no-worker.yaml" --check --diff -v +[ "$line" = "$run-shop-staging: would deploy" ] || fail "a rotated secret in a dry run: last line: $line" +[ "$(leaks)" = 0 ] || fail "a secret is in the output of a dry run with --diff -v" +deploy staging "$work/no-worker.yaml" -v +[ "$line" = "$run-shop-staging: deployed" ] || fail "a rotated secret: last line: $line" +[ "$(leaks)" = 0 ] || fail "a secret is in the output of a run that rotates one" +[ "$(value_of staging API_TOKEN)" = 'token-of-the-secret, rotated' ] || fail "the rotated secret did not reach web" +[ "$(stat -c %a "$stacks/$run-shop-staging/.env.secret.prev")" = 600 ] || fail ".env.secret.prev is not 0600" +deploy staging "$work/no-worker.yaml" -v +[ "$line" = "$run-shop-staging: unchanged" ] || fail "run again: last line: $line" +[ "$(leaks)" = 0 ] || fail "a secret is in the output of a run that changes nothing" +echo "✓ $case" + +case='a changed value that breaks the healthcheck, beside a rotated secret' +web_id=$(container staging web) +for file in .env .env.secret compose.yaml; do cp "$stacks/$run-shop-staging/$file" "$work/before$file"; done +secret op://acme/shop/staging/token 'token-of-the-secret, rotated twice' +environment staging 'env:' ' GREETING: hello' ' HEALTH: bad' " ODD: '${value//\'/\'\'}'" 'secrets:' \ + ' DB_PASSWORD: op://acme/shop/staging/password' ' API_TOKEN: op://acme/shop/staging/token' +deploy staging "$work/no-worker.yaml" +[ "$status" != 0 ] || fail "exit code 0" +[[ $line == "$run-shop-staging: rolled back: "*unhealthy* ]] || fail "last line: $line" +for file in .env .env.secret compose.yaml; do + cmp -s "$work/before$file" "$stacks/$run-shop-staging/$file" || fail "$file is not the one before" +done +[ "$(health_of staging web)" = healthy ] || fail "web is not healthy" +[ -z "$(value_of staging HEALTH)" ] || fail "web runs with HEALTH=$(value_of staging HEALTH)" +[ "$(value_of staging API_TOKEN)" = 'token-of-the-secret, rotated' ] || fail "web runs with the new secret" +[ "$(image_of staging web)" = "$web_v2" ] || fail "web does not run $web_v2" +echo "✓ $case" + +case='a secret that cannot be read' +snapshot() { find "$stacks/$run-shop-staging" -type f -exec sha256sum {} + | sort; } +before=$(snapshot) +environment staging 'env:' ' GREETING: hello' 'secrets:' ' DB_PASSWORD: op://acme/shop/staging/missing' +deploy staging "$work/no-worker.yaml" +[ "$status" != 0 ] || fail "exit code 0" +[[ $line == "$run-shop-staging: failed: "*"the secret DB_PASSWORD (op://acme/shop/staging/missing) could not be read: "*"no such item" ]] || + fail "last line: $line" +[ "$(snapshot)" = "$before" ] || fail "a file of the environment changed" +echo "✓ $case" + +case='a deploy of the files in place that fails' +# Nothing the playbook writes changes; web's data is broken by hand and web +# stopped, so that up starts it again and it never turns healthy. +environment staging 'env:' ' GREETING: hello' " ODD: '${value//\'/\'\'}'" 'secrets:' \ + ' DB_PASSWORD: op://acme/shop/staging/password' ' API_TOKEN: op://acme/shop/staging/token' +secret op://acme/shop/staging/token 'token-of-the-secret, rotated' +before=$(snapshot) +docker exec "$(container staging web)" rm /data/migrated +docker stop -t 1 "$(container staging web)" >/dev/null deploy staging "$work/no-worker.yaml" [ "$status" != 0 ] || fail "exit code 0" [[ $line == "$run-shop-staging: failed: "*unhealthy* ]] || fail "last line: $line" -cmp -s "$work/no-worker.yaml" "$stacks/$run-shop-staging/compose.yaml" || fail "compose.yaml was changed" -cmp -s "$work/prev.yaml" "$stacks/$run-shop-staging/compose.yaml.prev" || fail "compose.yaml.prev was changed" +[ "$(snapshot)" = "$before" ] || fail "a file of the environment changed" +docker run --rm --name "$run-probe" -v "$run-shop-staging_data:/data" busybox:1.37 sh -c 'echo ran >> /data/migrated' echo "✓ $case" case='a first deploy whose migrate fails, beside a container of the project' @@ -356,24 +482,29 @@ echo "✓ $case" case='invalid variables' cp "$stacks/$run-shop-staging/compose.yaml" "$work/in-place.yaml" -deploy staging "$work/v1.yaml" -i 127.0.0.1, -[ "$status" != 0 ] || fail "two hosts: exit code 0" -[[ $line == "the stack: failed: "* ]] || fail "two hosts: last line: $line" deploy staging '' [ "$status" != 0 ] || fail "no compose file: exit code 0" [[ $line == "the stack: failed: "* ]] || fail "no compose file: last line: $line" +deploy nowhere "$work/v1.yaml" +[ "$status" != 0 ] || fail "no environment's file: exit code 0" +[[ $line == "$run-shop-nowhere: failed: "* ]] || fail "no environment's file: last line: $line" cmp -s "$work/in-place.yaml" "$stacks/$run-shop-staging/compose.yaml" || fail "compose.yaml was written" echo "✓ $case" case='an invalid stack or environment name' for name in "$run-Shop staging" "$run-shop pre-view" "$run-shop Staging"; do set -- $name - mkdir -p "$stacks/$1-$2" && touch "$stacks/$1-$2/.env" + environment "$2" stack=$1 deploy "$2" "$work/v1.yaml" [ "$status" != 0 ] || fail "$1-$2: exit code 0" [[ $line == "the stack: failed: "* ]] || fail "$1-$2: last line: $line" - [ ! -e "$stacks/$1-$2/compose.yaml" ] || fail "$1-$2: compose.yaml was written" + [ ! -e "$stacks/$1-$2" ] || fail "$1-$2: the directory was laid out" done +environment yml +mv "$work/env/yml.yaml" "$work/env/yml.yml" +envfile=$work/env/yml.yml deploy yml "$work/v1.yaml" +[ "$status" != 0 ] || fail "yml.yml: exit code 0" +[[ $line == "the stack: failed: "* ]] || fail "yml.yml: last line: $line" echo "✓ $case" case='a deploy that leaves no service to start' From 65f09e5b027caba757d4a27041af3fd35bccaca8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:06:42 +0100 Subject: [PATCH 54/91] Index: append PLX-Stack/PreparedHost, which the stack playbook's header cites; ship regenerates the file at the cut Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/standard-index.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/lib/src/standard-index.json b/packages/lib/src/standard-index.json index ebd23ff5..541513ff 100644 --- a/packages/lib/src/standard-index.json +++ b/packages/lib/src/standard-index.json @@ -254,6 +254,7 @@ "PLX-Stack/EnvironmentFile", "PLX-Stack/EnvironmentParity", "PLX-Stack/EnvironmentCoverage", - "PLX-Stack/HostnamePort" + "PLX-Stack/HostnamePort", + "PLX-Stack/PreparedHost" ] } From 2fa626acf0c007ea67884249584ec3df6d6e07c4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:07:51 +0100 Subject: [PATCH 55/91] The stack playbook deploys from an environment's file The playbook takes the environment's file (stack_environment_file) in place of the environment's name and an inventory: a first play where it runs reads the file, refuses one it cannot write faithfully, resolves each pointer under `secrets` with `op read`, and adds the host `host` names, as the user it names or plexus_deploy_user, which the role deploy_user now gives a default. On the host it creates the environment's directory, writes .env from `env` with the project name and .env.secret from the secrets, each value double-quoted and escaped so that Compose reads it back as written, keeps the previous copy of each of the three files that changes, and on a failed deploy restores them together. No task that holds a secret prints it. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/playbooks/stack.yml | 140 ++++++++------ .../roles/deploy_user/defaults/main.yml | 10 +- .../platform/roles/stack/defaults/main.yml | 13 +- .../roles/stack/tasks/environment.yml | 104 +++++++++++ ansible/platform/roles/stack/tasks/main.yml | 173 +++++++++++------- ansible/platform/roles/stack/tasks/result.yml | 6 + .../platform/roles/stack/templates/dotenv.j2 | 8 + ansible/platform/roles/stack/vars/main.yml | 11 ++ 8 files changed, 337 insertions(+), 128 deletions(-) create mode 100644 ansible/platform/roles/stack/tasks/environment.yml create mode 100644 ansible/platform/roles/stack/tasks/result.yml create mode 100644 ansible/platform/roles/stack/templates/dotenv.j2 create mode 100644 ansible/platform/roles/stack/vars/main.yml diff --git a/ansible/platform/playbooks/stack.yml b/ansible/platform/playbooks/stack.yml index 13847f3c..43d8a58d 100644 --- a/ansible/platform/playbooks/stack.yml +++ b/ansible/platform/playbooks/stack.yml @@ -1,39 +1,54 @@ --- -# The stack playbook: deploys one environment of one stack onto one host. -# It runs where the deploy starts, a CI job or a person's machine, connects -# as the deploy user, and is never installed on the host. The deploy itself -# is the role plexus.platform.stack; the platform playbook -# (plexus.platform.playbook) lays the environment out before its first deploy. +# The stack playbook: deploys one environment of one stack onto its host. It +# runs where the deploy starts, a CI job or a person's machine, reads there the +# environment's file and the rendered compose file, connects to the host the +# file names as the deploy user, and is never installed on the host. The +# deploy is the role plexus.platform.stack. # -# ansible-playbook -i deploy@app-1.example.com, plexus.platform.stack \ -# -e stack_name=shop -e stack_environment=staging -e stack_compose_file=./compose.yaml +# ansible-playbook plexus.platform.stack -e stack_name=shop \ +# -e stack_environment_file=stack/staging.yaml -e stack_compose_file=./compose.yaml # -# Variables, documented in the role's defaults: stack_name, stack_environment -# and stack_compose_file, given on every run; stack_root (/opt/stacks) and -# stack_wait_timeout (60 seconds). +# Variables, documented in the role's defaults: stack_name, +# stack_environment_file and stack_compose_file, given on every run; the +# environment is named after its file (staging.yaml is staging). Further +# stack_root (/opt/stacks) and stack_wait_timeout (60 seconds). It takes no +# inventory: the one host is the file's `host`, [user@]address[:port], reached +# as the user it names, else as plexus_deploy_user (the role deploy_user's +# default, plexus), on the port it names, else 22. Arguments of +# ansible-playbook for the connection, such as --ssh-common-args or +# --private-key, apply to it. # -# What it expects on the host: the directory /-, -# which the user it connects as may write, holding the .env (and .env.secret -# where the environment has secrets) that the platform playbook writes; Docker -# with its compose plugin, which that user may run (the docker group); and -# Python. It uses no privilege escalation. The compose project is -# -, the name the platform playbook writes into .env. +# What it expects where it runs: the vault's CLI, op, with a session or a +# token, where the environment has secrets. On the host, as the platform +# playbook prepares it (PLX-Stack/PreparedHost): the deploy user, owner of +# /opt/stacks; Docker with its compose plugin, which that user may run (the +# docker group); and Python. It uses no privilege escalation. # -# In order: -# 1. Checks its variables, that the inventory holds one host, and that the -# directory and its .env are there. -# 2. Compares the compose file with the compose.yaml in place. Where they are -# the same, 3 to 5 are left out. -# 3. Keeps the compose.yaml in place as compose.yaml.prev and writes the new one. -# 4. Pulls the images, so that an image that cannot be had fails the deploy -# before migrate runs, and a tag that moved since the last deploy is -# fetched, which run and up, pulling only what is missing, would not do. -# Where the file is the one in place, nothing is pulled, so a tag that -# moved is fetched only by a deploy that changes the file. -# 5. Runs the service `migrate` once, where the file has one, and removes its -# container; where it fails, the line says its exit code and the last line -# it wrote. -# 6. Brings up every service Compose starts by itself, `migrate` excepted, with +# In order, where it runs: +# 1. Checks its variables, and reads the environment's file and checks that +# it can write it: a map of `host`, `hostname`, a DNS name, `env`, names +# to strings, and `secrets`, names to op:// pointers; plx doctor checks +# the file whole. +# 2. Reads each pointer under `secrets` with `op read`, also in a dry run, +# and adds the host the file names. +# On the host, into /opt/stacks/-, the compose project of +# that name: +# 3. Creates the directory where it is missing, mode 0750. +# 4. Renders .env from `env`, with COMPOSE_PROJECT_NAME; .env.secret, mode +# 0600, from the secrets' values, where the environment has secrets or +# the directory holds one already; each value double-quoted and escaped +# (templates/dotenv.j2), so that Compose reads it back as written. +# Compares them, and the compose file, with the files in place: a file +# that changes is kept as .prev, all of them before the first is +# written, and then written, .env, .env.secret, compose.yaml. +# 5. Pulls the images, where compose.yaml changed, so that an image that +# cannot be had fails the deploy before migrate runs, and a tag that moved +# since the last deploy is fetched, which run and up, pulling only what is +# missing, would not do. +# 6. Runs the service `migrate` once, where compose.yaml changed and has +# one, and removes its container; where it fails, the line says its exit +# code and the last line it wrote. +# 7. Brings up every service Compose starts by itself, `migrate` excepted, with # --no-deps, so that a service that depends on migrate's completion does # not run it again, and --remove-orphans, so that a service the file no # longer has goes. Then waits for every service that declares a @@ -41,29 +56,35 @@ # runs. stack_wait_timeout bounds the whole wait, and a healthcheck's # start_period does not extend it: a service that needs longer to turn # healthy needs the variable raised. Compose re-creates a container only -# where its service changed: an image pinned by digest that did not change -# leaves its line, and its container, as they were. Where no service is -# left to start, a stack of `migrate` alone or of none, it starts nothing -# and takes down whatever the project still runs; a take-down of something -# it ran counts as deployed, as a start does. -# A failure after 3 restores compose.yaml.prev and runs 6 again. After a first -# deploy, where there is no previous file, it removes the stack's containers -# and networks and the compose.yaml; the volumes stay. Where the file was the -# one in place, a failure undoes nothing; so a run after a rollback, with the -# same file, deploys it again and fails the same way. .env and .env.secret are -# the platform playbook's and are neither written nor restored here. +# where its service changed, its image or the files it loads: an image +# pinned by digest that did not change, and values that did not, leave +# the container as it was. Where no service is left to start, a stack of +# `migrate` alone or of none, it starts nothing and takes down whatever +# the project still runs; a take-down of something it ran counts as +# deployed, as a start does. +# A failure after the first write of 4 restores the files that run replaced, +# each from its .prev, removes a file it created, and runs 7 again. Where +# compose.yaml was not there before, a first deploy, it removes the stack's +# containers and networks and the compose.yaml instead; the volumes, .env and +# .env.secret stay. Where no file changed, a failure undoes nothing; so a run +# after a rollback, with the same files, deploys them again and fails the same +# way. A run in which nothing changed changes no file and re-creates no +# container. # -# Nothing locks an environment: two runs for the same environment at the same -# time are not supported, and can both fail, one undoing what the other made. -# What keeps them apart is the pipeline's own order, one deploy job per branch -# at a time. +# Nothing locks an environment as a whole: two runs for the same environment +# at the same time are not supported, and can both fail, one undoing what the +# other made. What keeps them apart is the pipeline's own order, one deploy job +# per branch at a time. +# +# No secret's value appears in the run's output, with -v or --diff either: +# every task that holds one prints nothing of it. # # The last task, Result, prints one line as its `msg`: -# -: deployed the file changed, or a container was started or +# -: deployed a file changed, or a container was started or # taken down; healthy # -: unchanged nothing changed, and healthy -# -: would deploy under --check, where compose.yaml would change -# -: rolled back: the previous compose.yaml is up and healthy again +# -: would deploy under --check, where a file would change +# -: rolled back: the previous files are up and healthy again # -: failed: nothing was rolled back, or the undo failed too # names the step that failed and the first line of its error, as in # `'Bring the stack up and wait for health' failed (rc 1): General error: @@ -71,11 +92,24 @@ # variables fails, the line begins `the stack:`. The task, and with it the # run, fails unless the line says deployed, unchanged or would deploy. # -# --check, with --diff, runs 1 and 2 and shows whether compose.yaml would -# change, and how. It pulls, migrates and starts nothing, so it says nothing -# about the images, migrate or health. +# --check, with --diff, runs 1 to 4 and shows whether .env, .env.secret and +# compose.yaml would change, and how, but for .env.secret. It writes nothing, +# and pulls, migrates and starts nothing, so it says nothing about the images, +# migrate or health. +- name: Read the environment + hosts: localhost + connection: local + gather_facts: false + vars_files: + - ../roles/deploy_user/defaults/main.yml # plexus_deploy_user + tasks: + - name: Read the environment's file and its secrets + ansible.builtin.include_role: + name: plexus.platform.stack + tasks_from: environment.yml + - name: Deploy one environment of a stack - hosts: all + hosts: stack_host gather_facts: false roles: - { role: plexus.platform.stack } diff --git a/ansible/platform/roles/deploy_user/defaults/main.yml b/ansible/platform/roles/deploy_user/defaults/main.yml index 250cc6a4..7d9c4730 100644 --- a/ansible/platform/roles/deploy_user/defaults/main.yml +++ b/ansible/platform/roles/deploy_user/defaults/main.yml @@ -5,15 +5,19 @@ # stack contract names for every environment (PLX-Stack/HostDirectory). # # The plexus_ variables are shared with other roles (plexus.host.docker adds -# the user to the docker group), so they keep that prefix and have no default -# here; set them in the operations repo's group variables: -# plexus_deploy_user the user's name +# the user to the docker group), so they keep that prefix; set them in the +# operations repo's group variables: # plexus_deploy_pubkey the public key the deployer connects with; unset or # empty: no key is authorized # plexus_ghcr_user the registry login the user pulls the stacks' images # plexus_ghcr_token with, renewed on every run; an unset or empty token: # no login, the images are public or an earlier login stands +# The user's name, by convention the same on every host: the stack playbook +# reads it from this file and connects as it where an environment's host names +# no user. +plexus_deploy_user: plexus # noqa: var-naming[no-role-prefix] + # Further groups for the deploy user, e.g. the group an image's sshd policy # admits logins from. deploy_user_groups: [] diff --git a/ansible/platform/roles/stack/defaults/main.yml b/ansible/platform/roles/stack/defaults/main.yml index a63da470..e2489a03 100644 --- a/ansible/platform/roles/stack/defaults/main.yml +++ b/ansible/platform/roles/stack/defaults/main.yml @@ -3,12 +3,15 @@ # plexus.platform.stack mounts; its header says what it does, in order. # # Given on every run, with no default (`-e`, as `plx deploy` passes them): -# stack_name the stack's name, as in `shop` -# stack_environment the environment's name, one lowercase word, as in `staging` -# stack_compose_file the stack's rendered compose file on the machine that -# runs the playbook, every app's image pinned by digest +# stack_name the stack's name, as in `shop` +# stack_environment_file the environment's file on the machine that runs +# the playbook, as in `stack/staging.yaml`; the +# environment is named after it +# stack_compose_file the stack's rendered compose file on that machine, +# every app's image pinned by digest -# Where the environments live on the host, each in /-. +# Where the environments live on the host, each in /- +# (PLX-Stack/HostDirectory; the role deploy_user gives the deploy user the same path). stack_root: /opt/stacks # How long, in seconds, the deploy waits for every service that declares a diff --git a/ansible/platform/roles/stack/tasks/environment.yml b/ansible/platform/roles/stack/tasks/environment.yml new file mode 100644 index 00000000..c3179719 --- /dev/null +++ b/ansible/platform/roles/stack/tasks/environment.yml @@ -0,0 +1,104 @@ +--- +# Steps 1 and 2 of the playbook's header, where the playbook runs: the +# variables, the environment's file, its secrets, and the one host it names, +# added to the group stack_host with what the deploy there reads. +- name: Read the environment + block: + - name: Check the variables + ansible.builtin.assert: + that: + - stack_name | default('') is match('^[a-z0-9][a-z0-9_-]*$') + - stack_environment_file | default('') | basename is match('^[a-z]+\.yaml$') + - stack_compose_file | default('') | length > 0 + fail_msg: >- + the stack playbook deploys one environment of a stack: a stack_name of lowercase letters, digits, - and _, + a stack_environment_file named after the environment, .yaml, and a stack_compose_file + quiet: true + + - name: Name the environment's project after the stack and the file + ansible.builtin.set_fact: + stack_project: "{{ stack_name }}-{{ stack_environment_file | basename | regex_replace('\\.yaml$', '') }}" + + - name: Read the environment's file + ansible.builtin.set_fact: + stack_file: "{{ lookup('ansible.builtin.file', stack_environment_file) | from_yaml }}" + + # What the playbook needs to write the files faithfully; plx doctor checks + # the file whole (packages/lib/src/environments.ts). The forms are the + # role's vars. + - name: Check the environment's file + vars: + file: "{{ stack_file if stack_file is mapping else {} }}" + env: "{{ file.env | default({}, true) }}" + secrets: "{{ file.secrets | default({}, true) }}" + names: "{{ (env.keys() | list) + (secrets.keys() | list) if env is mapping and secrets is mapping else [] }}" + ansible.builtin.assert: + that: + - stack_file is mapping + - file.keys() | difference(['host', 'hostname', 'env', 'secrets']) | length == 0 + - file.host | default('') is string + - file.host | default('') is match(stack_host_form) + - file.hostname is not defined or (file.hostname is string and file.hostname | lower is match(stack_hostname_form)) + - env is mapping and env.values() | select('string') | list | length == env | length + - secrets is mapping and secrets.values() | select('string') | select('match', 'op://') | list | length == secrets | length + - names | reject('match', '^[A-Za-z_][A-Za-z0-9_]*$') | list | length == 0 + - names | length == names | unique | length + # Of the names PLATFORM_VARIABLES lists (packages/lib/src/environments.ts), the two this playbook writes. + - names | intersect(['COMPOSE_PROJECT_NAME', 'PLEXUS_LOOPBACK_PORT']) | length == 0 + fail_msg: >- + {{ stack_environment_file }} is not an environment the playbook can write: a map of host, an SSH destination + [user@]address[:port], hostname, a DNS name, env, names to strings, and secrets, names to op:// pointers, no + name in both and none the playbook writes itself; plx doctor says what is wrong + quiet: true + + # Each pointer resolved where the playbook runs, by the vault's CLI and the + # session or token it finds there; the value as the vault holds it, a + # trailing newline included. Read in a dry run too, to tell whether + # .env.secret would change. + - name: Resolve the secrets + ansible.builtin.command: + argv: [op, read, --no-newline, "{{ item.value }}"] + strip_empty_ends: false + loop: "{{ stack_file.secrets | default({}, true) | dict2items }}" + register: stack_reads + changed_when: false + failed_when: false + check_mode: false + no_log: true + + - name: Check that every secret was read + when: stack_failed_reads | length > 0 + vars: + stack_failed_reads: "{{ stack_reads.results | default([]) | rejectattr('rc', 'equalto', 0) | list }}" + ansible.builtin.fail: + msg: >- + the secret {{ stack_failed_reads[0].item.key }} ({{ stack_failed_reads[0].item.value }}) could not be read: + {{ (stack_failed_reads[0].stderr | default('', true) or stack_failed_reads[0].msg | default('no message')).splitlines() | last }} + + - name: Add the environment's host + vars: + target: "{{ stack_file.host | regex_search(stack_host_form, '\\1', '\\2', '\\3', '\\4', '\\5', '\\6') }}" + ansible.builtin.add_host: + name: "{{ target[1] or target[3] or target[5] }}" + groups: [stack_host] + ansible_host: "{{ target[1] or target[3] or target[5] }}" + ansible_user: "{{ target[0] or plexus_deploy_user }}" + ansible_port: "{{ target[2] or target[4] or 22 }}" + stack_project: "{{ stack_project }}" + stack_hostname: "{{ stack_file.hostname | default('') | lower }}" + stack_env: "{{ stack_file.env | default({}, true) }}" + stack_secrets: >- + {{ dict(stack_reads.results | default([]) | map(attribute='item.key') + | zip(stack_reads.results | default([]) | map(attribute='stdout'))) }} + no_log: true + changed_when: false + + rescue: + - name: Note why the environment was not read + ansible.builtin.set_fact: + stack_outcome: >- + failed: '{{ ansible_failed_task.name }}' failed: + {{ (ansible_failed_result.msg | default('no message') | string).splitlines() | first | default('') }} + + - name: Say why + ansible.builtin.include_tasks: result.yml diff --git a/ansible/platform/roles/stack/tasks/main.yml b/ansible/platform/roles/stack/tasks/main.yml index 5cbd26c3..d3c9b91e 100644 --- a/ansible/platform/roles/stack/tasks/main.yml +++ b/ansible/platform/roles/stack/tasks/main.yml @@ -1,70 +1,105 @@ --- -- name: Deploy, and roll back what a failure after the write of compose.yaml leaves +# Steps 3 to 7 of the playbook's header, on the environment's host as the +# deploy user; tasks/environment.yml has read the environment before. +- name: Deploy, and roll back what a failure after the first write leaves block: - - name: Check the variables - ansible.builtin.assert: - that: - - ansible_play_hosts_all | length == 1 - - stack_name | default('') is match('^[a-z0-9][a-z0-9_-]*$') - - stack_environment | default('') is match('^[a-z0-9]+$') - - stack_compose_file | default('') | length > 0 - fail_msg: >- - the stack playbook deploys one environment onto one host: an inventory of one host, a stack_name of - lowercase letters, digits, - and _, a stack_environment of lowercase letters and digits, and a - stack_compose_file - quiet: true - - - name: Resolve the environment's project, directory and compose file + - name: Resolve the environment's directory and files ansible.builtin.set_fact: - stack_project: "{{ stack_name }}-{{ stack_environment }}" - stack_dir: "{{ stack_root }}/{{ stack_name }}-{{ stack_environment }}" + stack_dir: "{{ stack_root }}/{{ stack_project }}" stack_compose: "{{ stack_compose_file | ansible.builtin.realpath }}" + stack_files: [.env, .env.secret, compose.yaml] + stack_replaced: [] - - name: Look for the environment's directory + - name: Look for the deploy root ansible.builtin.stat: - path: "{{ stack_dir }}" - register: stack_laid_out + path: "{{ stack_root }}" + register: stack_root_found - - name: Look for the environment's .env - ansible.builtin.stat: - path: "{{ stack_dir }}/.env" - register: stack_env - - - name: Check that the platform playbook has laid the environment out + - name: Check that the platform has prepared the host ansible.builtin.assert: that: - - stack_laid_out.stat.isdir | default(false) - - stack_env.stat.exists + - stack_root_found.stat.isdir | default(false) + - stack_root_found.stat.writeable fail_msg: >- - {{ stack_dir ~ ('/.env' if stack_laid_out.stat.exists else '') }} is not there; the platform playbook - lays out an environment's directory and writes its .env before the environment's first deploy + {{ stack_root }} is not there, or not the deploy user's; the platform playbook prepares a host for stacks quiet: true - - name: Read the compose file + - name: Lay out the environment's directory + ansible.builtin.file: + path: "{{ stack_dir }}" + state: directory + mode: "0750" + + # COMPOSE_PROJECT_NAME is one of the names PLATFORM_VARIABLES lists + # (packages/lib/src/environments.ts). + - name: Render .env and read the compose file ansible.builtin.set_fact: stack_text: "{{ lookup('ansible.builtin.file', stack_compose, rstrip=false) }}" + stack_env_text: >- + {{ lookup('ansible.builtin.template', 'dotenv.j2', + template_vars={'variables': stack_env | combine({'COMPOSE_PROJECT_NAME': stack_project})}) }} - - name: Look for the compose.yaml in place + - name: Render .env.secret + ansible.builtin.set_fact: + stack_secret_text: "{{ lookup('ansible.builtin.template', 'dotenv.j2', template_vars={'variables': stack_secrets}) }}" + no_log: true + + - name: Look for the files in place ansible.builtin.stat: - path: "{{ stack_dir }}/compose.yaml" + path: "{{ stack_dir }}/{{ item }}" checksum_algorithm: sha1 - register: stack_present + loop: "{{ stack_files }}" + register: stack_in_place + + # .env.secret where the environment has secrets, or one is there already. + - name: Note the files that change + when: >- + (item.item != '.env.secret' or stack_secrets | length > 0 or item.stat.exists) + and (not item.stat.exists or item.stat.checksum != stack_new[item.item] | hash('sha1')) + vars: + stack_new: { .env: "{{ stack_env_text }}", .env.secret: "{{ stack_secret_text }}", compose.yaml: "{{ stack_text }}" } + ansible.builtin.set_fact: + stack_replaced: "{{ stack_replaced + [item.item] }}" + loop: "{{ stack_in_place.results }}" + loop_control: + label: "{{ item.item }}" - # Nothing to pull or migrate where the file is the one in place: Compose - # re-creates nothing then, and the run reports no change. - - name: Compare the compose file with the one in place + - name: Note which files were there ansible.builtin.set_fact: - stack_changed: "{{ not stack_present.stat.exists or stack_present.stat.checksum != stack_text | hash('sha1') }}" + stack_existed: "{{ dict(stack_files | zip(stack_in_place.results | map(attribute='stat.exists'))) }}" + stack_changed: "{{ 'compose.yaml' in stack_replaced }}" stack_services: "{{ (stack_text | from_yaml).services | default({}, true) }}" - - name: Keep the compose.yaml in place as the previous copy - when: stack_changed and stack_present.stat.exists + - name: Keep each file that changes as its previous copy + when: stack_existed[item] ansible.builtin.copy: - src: "{{ stack_dir }}/compose.yaml" - dest: "{{ stack_dir }}/compose.yaml.prev" + src: "{{ stack_dir }}/{{ item }}" + dest: "{{ stack_dir }}/{{ item }}.prev" remote_src: true + mode: "{{ '0600' if item == '.env.secret' else '0640' }}" + loop: "{{ stack_replaced }}" + diff: false + + - name: Note that a failure from here on is undone + ansible.builtin.set_fact: + stack_written: "{{ stack_replaced }}" + + - name: Write .env + when: "'.env' in stack_replaced" + ansible.builtin.copy: + content: "{{ stack_env_text }}" + dest: "{{ stack_dir }}/.env" mode: "0640" + - name: Write .env.secret + when: "'.env.secret' in stack_replaced" + ansible.builtin.copy: + content: "{{ stack_secret_text }}" + dest: "{{ stack_dir }}/.env.secret" + mode: "0600" + no_log: true + diff: false + - name: Write compose.yaml when: stack_changed ansible.builtin.copy: @@ -72,11 +107,7 @@ dest: "{{ stack_dir }}/compose.yaml" mode: "0640" - - name: Note that a failure from here on is undone - ansible.builtin.set_fact: - stack_written: "{{ stack_changed }}" - - # A dry run stops here: Compose would run against the file in place, + # A dry run stops here: Compose would run against the files in place, # which the dry run has not replaced. - name: Pull, migrate and bring the stack up when: not ansible_check_mode @@ -126,8 +157,8 @@ - name: Note that the environment is deployed ansible.builtin.set_fact: stack_outcome: >- - {{ ('would deploy' if stack_changed else 'unchanged') if ansible_check_mode - else ('deployed' if stack_changed or stack_up is changed or stack_down is changed else 'unchanged') }} + {{ ('would deploy' if stack_replaced else 'unchanged') if ansible_check_mode + else ('deployed' if stack_replaced or stack_up is changed or stack_down is changed else 'unchanged') }} rescue: - name: Note why the deploy failed @@ -137,30 +168,41 @@ {{- (' (rc ' ~ ansible_failed_result.rc ~ ')') if ansible_failed_result.rc is defined else '' }}: {{ (ansible_failed_result.msg | default('no message') | string).splitlines() | first | default('') }} - # Back to the previous compose.yaml, or, after a first deploy, to none: - # its containers and networks go, its volumes stay. - - name: Undo the write of compose.yaml - when: stack_written | default(false) + # Where compose.yaml was there before, back to the files it ran with: each + # file the run replaced from its previous copy, and one it created removed. + # After a first deploy, to no compose.yaml: its containers and networks go, + # its volumes stay, and so do .env and .env.secret. + - name: Undo the writes + when: stack_written | default([]) | length > 0 block: - - name: Restore the previous compose.yaml - when: stack_present.stat.exists + - name: Restore the files the run replaced + when: stack_existed['compose.yaml'] and stack_existed[item] ansible.builtin.copy: - src: "{{ stack_dir }}/compose.yaml.prev" - dest: "{{ stack_dir }}/compose.yaml" + src: "{{ stack_dir }}/{{ item }}.prev" + dest: "{{ stack_dir }}/{{ item }}" remote_src: true - mode: "0640" + mode: "{{ '0600' if item == '.env.secret' else '0640' }}" + loop: "{{ stack_written }}" + diff: false + + - name: Remove the files the run created + when: stack_existed['compose.yaml'] and not stack_existed[item] + ansible.builtin.file: + path: "{{ stack_dir }}/{{ item }}" + state: absent + loop: "{{ stack_written }}" - name: Bring the previous stack up - when: stack_present.stat.exists + when: stack_existed['compose.yaml'] ansible.builtin.include_tasks: up.yml - name: Note that the environment is rolled back - when: stack_present.stat.exists + when: stack_existed['compose.yaml'] ansible.builtin.set_fact: stack_outcome: "rolled back: {{ stack_outcome | regex_replace('^failed: ', '') }}" - name: Take down what the first deploy started - when: not stack_present.stat.exists + when: not stack_existed['compose.yaml'] community.docker.docker_compose_v2: project_src: "{{ stack_dir }}" project_name: "{{ stack_project }}" @@ -168,7 +210,7 @@ remove_orphans: true - name: Remove the compose.yaml of the first deploy - when: not stack_present.stat.exists + when: not stack_existed['compose.yaml'] ansible.builtin.file: path: "{{ stack_dir }}/compose.yaml" state: absent @@ -180,8 +222,5 @@ {{ stack_outcome }}; the undo failed too, at '{{ ansible_failed_task.name }}': {{ (ansible_failed_result.msg | default('no message') | string).splitlines() | first | default('') }} -# The one line `plx deploy` reads (the playbook's header says its form). -- name: Result - ansible.builtin.debug: - msg: "{{ stack_project | default('the stack') }}: {{ stack_outcome }}" - failed_when: stack_outcome not in ['deployed', 'unchanged', 'would deploy'] +- name: Say how the deploy ended + ansible.builtin.include_tasks: result.yml diff --git a/ansible/platform/roles/stack/tasks/result.yml b/ansible/platform/roles/stack/tasks/result.yml new file mode 100644 index 00000000..0d590b8f --- /dev/null +++ b/ansible/platform/roles/stack/tasks/result.yml @@ -0,0 +1,6 @@ +--- +# The one line `plx deploy` reads (the playbook's header says its form). +- name: Result + ansible.builtin.debug: + msg: "{{ stack_project | default('the stack') }}: {{ stack_outcome }}" + failed_when: stack_outcome not in ['deployed', 'unchanged', 'would deploy'] diff --git a/ansible/platform/roles/stack/templates/dotenv.j2 b/ansible/platform/roles/stack/templates/dotenv.j2 new file mode 100644 index 00000000..a830ae06 --- /dev/null +++ b/ansible/platform/roles/stack/templates/dotenv.j2 @@ -0,0 +1,8 @@ +{#- `variables` as a dotenv file Compose reads, as .env and .env.secret: a line + NAME="value" per name, in the order of the names. Inside the double quotes + a backslash, a double quote, a $ and the line breaks and tabs are escaped, + so that Compose reads every value back as written, from env_file and for + interpolation alike, and interpolates nothing inside one. -#} +{% for name, value in variables | dictsort(true) %} +{{ name }}="{{ value | string | replace('\\', '\\\\') | replace('"', '\\"') | replace('$', '\\$') | replace('\n', '\\n') | replace('\r', '\\r') | replace('\t', '\\t') }}" +{% endfor %} diff --git a/ansible/platform/roles/stack/vars/main.yml b/ansible/platform/roles/stack/vars/main.yml new file mode 100644 index 00000000..16a1d671 --- /dev/null +++ b/ansible/platform/roles/stack/vars/main.yml @@ -0,0 +1,11 @@ +--- +# The forms tasks/environment.yml holds an environment's file to. +# host: [user@]address[:port], an IPv6 address in brackets where a port +# follows; the groups are the user, a bracketed address, its port, an address +# without a colon, its port, and a bare IPv6 address. +stack_host_form: "^(?:([A-Za-z0-9_][A-Za-z0-9._-]*)@)?\ + (?:\\[([0-9A-Fa-f:.]+)\\](?::([0-9]+))?\ + |([A-Za-z0-9][A-Za-z0-9.-]*)(?::([0-9]+))?\ + |([0-9A-Fa-f.]*:[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*))$" +# hostname, lowercased: a DNS name, labels of letters, digits and -. +stack_hostname_form: '^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)*[a-z0-9]([a-z0-9-]*[a-z0-9])?$' From a6b4836a2e3f02f815cd0163ba431de0565316a0 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:09:48 +0100 Subject: [PATCH 56/91] The image of a prepared host is shared by the tests of both playbooks host-image.sh builds what platform-playbook.sh built for itself, with Docker's CLI and compose plugin and PyYAML added, and Caddy without a site, so that it listens on nothing until the platform playbook configures it. The platform playbook's test mounts its stand-in for docker over the CLI; the stack playbook's test will run the real one against this machine's daemon. Co-Authored-By: Claude Opus 5.5 --- tests/host-image.sh | 44 +++++++++++++++++++++++ tests/platform-playbook.sh | 72 +++++++++++--------------------------- 2 files changed, 65 insertions(+), 51 deletions(-) create mode 100644 tests/host-image.sh diff --git a/tests/host-image.sh b/tests/host-image.sh new file mode 100644 index 00000000..3091101b --- /dev/null +++ b/tests/host-image.sh @@ -0,0 +1,44 @@ +# Sourced by the tests of plexus.platform's two playbooks (platform-playbook.sh, +# stack-playbook.sh): the image of a host they run the playbooks against, a +# container of this machine's Docker daemon. Debian with systemd, sudo, curl +# and Python with PyYAML; Caddy's binary and unit as its package installs them, +# without a site, so that it listens on nothing but its admin endpoint until +# the platform playbook configures it; and Docker's CLI with its compose +# plugin, which a test without a daemon for the host replaces by a stand-in. +# +# host_image : builds it, its output in $work/build; fails where debian:13, +# caddy:2, docker:29-cli or Debian's packages are not to be had. +host_image() { + mkdir -p "$work/image" + cat >"$work/image/Dockerfile" <<'EOF' +FROM caddy:2 AS caddy +FROM docker:29-cli AS docker +FROM debian:13 +RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \ + systemd systemd-sysv python3 python3-yaml sudo curl >/dev/null && rm -rf /var/lib/apt/lists/* +COPY --from=caddy /usr/bin/caddy /usr/bin/caddy +COPY --from=docker /usr/local/bin/docker /usr/local/bin/docker +COPY --from=docker /usr/local/libexec/docker/cli-plugins/docker-compose /usr/local/libexec/docker/cli-plugins/docker-compose +COPY caddy.service /etc/systemd/system/caddy.service +RUN useradd --system --home-dir /var/lib/caddy --create-home --shell /usr/sbin/nologin caddy \ + && mkdir /etc/caddy && printf '# The package default, without its site.\n' >/etc/caddy/Caddyfile \ + && systemctl enable caddy +CMD ["sh", "-c", "mount -o remount,rw /sys/fs/cgroup && exec /sbin/init"] +EOF + # The unit of Caddy's Debian package, without its sandboxing. + cat >"$work/image/caddy.service" <<'EOF' +[Unit] +Description=Caddy +After=network.target +[Service] +Type=notify +User=caddy +Group=caddy +ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile +ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile --force +TimeoutStopSec=5s +[Install] +WantedBy=multi-user.target +EOF + docker build -q -t "$1" "$work/image" >"$work/build" 2>&1 +} diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh index 5f758d3e..90af74b8 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -1,21 +1,21 @@ #!/usr/bin/env bash # The platform playbook (plexus.platform.playbook) against hosts that are -# containers of this machine's Docker daemon: Debian with systemd, sudo, and -# Caddy's binary and unit as its package installs them, reached by Ansible's -# docker connection. It runs the platform layer's roles (--tags platform) but -# caddy, whose apt repository would need the network on every run, and reads -# users, directories, sudo rules, the proxy's routes as curl on the host gets -# them, and the files of a deployment. A host's `docker` is a stand-in that -# records its arguments, so that a run that starts or re-creates nothing can be -# seen to: the hosts have no Docker daemon of their own. +# containers of this machine's Docker daemon (the image of host-image.sh), +# reached by Ansible's docker connection. It runs the platform layer's roles +# (--tags platform) but caddy, whose apt repository would need the network on +# every run, and reads users, directories, sudo rules, the proxy's routes as +# curl on the host gets them, and the files of a deployment. A host's `docker` +# is a stand-in that records its arguments, so that a run that starts or +# re-creates nothing can be seen to: the hosts have no Docker daemon of their +# own. # # Run by `mise test` (its task test-ansible), beside the stack playbook's # test. It needs a Docker daemon that lets a container run systemd (the # capability SYS_ADMIN, AppArmor unconfined, a cgroup namespace of its own), -# and the network once for debian:13, caddy:2 and Debian's packages; where -# either is missing, it says so and passes. Every container and image it -# creates is named plxplatform-…, publishes no port, and is removed when -# it ends, whether a case failed or not. +# and the network once for debian:13, caddy:2, docker:29-cli and Debian's +# packages; where either is missing, it says so and passes. Every container +# and image it creates is named plxplatform-…, publishes no port, and is +# removed when it ends, whether a case failed or not. set -euo pipefail cd "$(dirname "$0")/.." @@ -41,44 +41,13 @@ fail() { exit 1 } -# The host's image: what a Debian host has when the platform layer's roles run -# on it, the proxy included, and the stand-in for docker. -mkdir "$work/image" -cat >"$work/image/Dockerfile" <<'EOF' -FROM caddy:2 AS caddy -FROM debian:13 -RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \ - systemd systemd-sysv python3 sudo curl >/dev/null && rm -rf /var/lib/apt/lists/* -COPY --from=caddy /usr/bin/caddy /usr/bin/caddy -COPY caddy.service /etc/systemd/system/caddy.service -COPY docker /usr/local/bin/docker -RUN useradd --system --home-dir /var/lib/caddy --create-home --shell /usr/sbin/nologin caddy \ - && mkdir /etc/caddy && printf ':80 {\n\trespond "the package default"\n}\n' >/etc/caddy/Caddyfile \ - && systemctl enable caddy -CMD ["sh", "-c", "mount -o remount,rw /sys/fs/cgroup && exec /sbin/init"] -EOF -# The unit of Caddy's Debian package, without its sandboxing. -cat >"$work/image/caddy.service" <<'EOF' -[Unit] -Description=Caddy -After=network.target -[Service] -Type=notify -User=caddy -Group=caddy -ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile -ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile --force -TimeoutStopSec=5s -[Install] -WantedBy=multi-user.target -EOF -cat >"$work/image/docker" <<'EOF' -#!/bin/sh -echo "$*" >>/var/log/docker-calls -EOF -chmod +x "$work/image/docker" -if ! docker build -q -t "$run:host" "$work/image" >"$work/build" 2>&1; then - echo "platform-playbook: the host's image could not be built (debian:13, caddy:2 or Debian's packages not to be had); skipped" +# The host's image (host-image.sh), with a stand-in for docker mounted over +# its CLI in every host. +. tests/host-image.sh +printf '#!/bin/sh\necho "$*" >>/var/log/docker-calls\n' >"$work/docker" +chmod +x "$work/docker" +if ! host_image "$run:host"; then + echo "platform-playbook: the host's image could not be built (debian:13, caddy:2, docker:29-cli or Debian's packages not to be had); skipped" sed 's/^/ /' "$work/build" exit 0 fi @@ -87,7 +56,8 @@ fi # $work/.yml; the name is the container's, $run-. host() { docker run -d --name "$run-$1" --hostname "$1" --cgroupns=private --cap-add SYS_ADMIN \ - --security-opt apparmor=unconfined --tmpfs /run --tmpfs /run/lock -e container=docker "$run:host" >/dev/null + --security-opt apparmor=unconfined --tmpfs /run --tmpfs /run/lock -e container=docker \ + -v "$work/docker:/usr/local/bin/docker:ro" "$run:host" >/dev/null if ! timeout 60 docker exec "$run-$1" systemctl is-system-running --wait >/dev/null 2>&1 && ! docker exec "$run-$1" systemctl is-active -q caddy 2>/dev/null; then echo "platform-playbook: systemd does not boot in a container on this Docker daemon; skipped" From a76519cd1016b3ef3677ab997269194aee761862 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:17:57 +0100 Subject: [PATCH 57/91] The stack playbook's test deploys environments with a hostname onto a prepared host A second part runs the playbook against a host the platform playbook prepared, a container booted with systemd in this machine's network, whose proxy listens on 127.0.0.1 and ports of the run's own: a first deploy takes the lowest port of the range and writes the route, which serves the environment and refuses /healthz; a run in which nothing changed changes no file and reloads nothing; two first deploys started at once end with different ports; a hostname another environment serves is refused; a changed value that breaks the healthcheck is rolled back and its route kept; a port a directory holds is kept; no free port; a route the proxy refuses; a dry run. Co-Authored-By: Claude Opus 5.5 --- tests/stack-playbook.sh | 199 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 199 insertions(+) diff --git a/tests/stack-playbook.sh b/tests/stack-playbook.sh index 8e51c3b7..c4d07acc 100755 --- a/tests/stack-playbook.sh +++ b/tests/stack-playbook.sh @@ -533,3 +533,202 @@ if ansible-galaxy collection install --no-deps -p "$work/lowest" "community.dock else echo "stack-playbook: community.docker $lowest could not be fetched from Galaxy; $case skipped" fi + +# The second part, on a host the platform playbook prepared (the header). +. tests/host-image.sh +skip() { echo "stack-playbook: $*; the cases with a hostname skipped"; exit 0; } +[ -S /var/run/docker.sock ] || skip "this daemon's socket is not /var/run/docker.sock" +host_image "$run:host" || { sed 's/^/ /' "$work/build"; skip "the host's image could not be built"; } +# free: a port of this machine that nothing listens on, as the kernel hands one out. +free() { python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])'; } +admin=$(free) http=$(free) https=$(free) legacy=$(free) +# The environments' ports: ten in a row that nothing listens on, below the kernel's. +for _ in $(seq 50); do + first=$((21000 + RANDOM % 9000)) + [ -n "$(ss -Hltn "sport >= :$first and sport <= :$((first + 9))")" ] || break +done +range=$first-$((first + 9)) + +host=$run-host +mkdir -p "$work/caddy.service.d" +printf '[Service]\nEnvironment=CADDY_ADMIN=127.0.0.1:%s\n' "$admin" >"$work/caddy.service.d/admin.conf" +docker create --name "$host" --network host --cgroupns=private --cap-add SYS_ADMIN --security-opt apparmor=unconfined \ + --tmpfs /run --tmpfs /run/lock -e container=docker -v /var/run/docker.sock:/docker.sock "$run:host" >/dev/null +docker cp -q "$work/caddy.service.d" "$host:/etc/systemd/system/" +docker start "$host" >/dev/null +if ! timeout 60 docker exec "$host" systemctl is-system-running --wait >/dev/null 2>&1 && + ! docker exec "$host" systemctl is-active -q caddy 2>/dev/null; then + skip "systemd does not boot in a container on this Docker daemon" +fi +cat >"$work/host.yml" <: a command on the prepared host as root; as_deploy : as the deploy user. +on() { docker exec "$host" "$@"; } +as_deploy() { docker exec -u plexus "$host" "$@"; } +# get : the body and status of a request the prepared host's proxy serves. +get() { curl -sk -m 5 -w ' %{http_code}' --resolve "$1:$https:127.0.0.1" "https://$1:$https$2" || true; } +# The port an environment's .env holds; how often the proxy was reloaded. +port_of() { on sed -n 's/^PLEXUS_LOOPBACK_PORT="\{0,1\}\([0-9]*\)"\{0,1\}$/\1/p' "/opt/stacks/$1/.env"; } +reloads() { on journalctl -q --no-pager -u caddy | grep -c Reloading || true; } +# Every file of the environments and the routes, with its size and time. +files() { on sh -c 'find /opt/stacks /etc/caddy/stacks -exec stat -c "%n %s %y" {} + | sort'; } + +case='a host the platform playbook prepares' +status=0 +timeout 600 ansible-playbook -i "$work/host.yml" --tags platform --skip-tags caddy plexus.platform.playbook "$work/out" 2>&1 || status=$? +[ "$status" = 0 ] || fail "the platform playbook: exit code $status" +# Beyond what the platform playbook does: this daemon's socket for the deploy +# user, in place of a daemon of the host's own, and the proxy on 127.0.0.1 and +# the run's ports, with certificates from its own CA. +gid=$(stat -c %g /var/run/docker.sock) +on sh -c "ln -s /docker.sock /run/docker.sock && { getent group $gid >/dev/null || groupadd -g $gid docker; } && + usermod -aG \$(getent group $gid | cut -d: -f1) plexus" +on sh -c "printf '{\n\thttp_port $http\n\thttps_port $https\n\tdefault_bind 127.0.0.1\n\tlocal_certs\n\tskip_install_trust\n}\n' | + cat - /etc/caddy/Caddyfile >/etc/caddy/Caddyfile.run && mv /etc/caddy/Caddyfile.run /etc/caddy/Caddyfile && systemctl reload caddy" || + fail "the proxy does not take the run's ports" +echo "✓ $case" + +# The stack on the prepared host: web serves GREETING on / and turns healthy +# where /healthz answers and HEALTH is not bad. +cat >"$work/site.yaml" </www/index.html && echo ok >/www/healthz && exec httpd -f -p 3000 -h /www"] + env_file: + - path: .env + - path: .env.secret + required: false + ports: ["127.0.0.1:\${PLEXUS_LOOPBACK_PORT:?set by the deploy}:3000"] + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:3000/healthz >/dev/null && ! printenv HEALTH | grep -qx bad"] + interval: 1s + retries: 3 +YAML +# site […]: the environment's file, its host the prepared host. +site() { mkdir -p "$work/host/$1"; { echo "host: $host"; printf '%s\n' "${@:3}"; } >"$work/host/$1/$2.yaml"; } +# play_on [arguments]: one run against the +# prepared host; deploy_on [arguments]: the same, with +# $status and $line as deploy sets them. +play_on() { + ansible-playbook -i "$work/host.yml" -e stack_name="$2" -e stack_environment_file="$work/host/$2/$3.yaml" \ + -e stack_compose_file="$work/site.yaml" -e stack_port_range="$range" "${@:4}" plexus.platform.stack "$1" 2>&1 +} +deploy_on() { + status=0 + play_on "$work/out" "$@" || status=$? + line=$(sed -n 's/^ *"msg": "\(.*\)"$/\1/p' "$work/out" | tail -1) +} + +case='a first deploy that takes a port and writes the route' +site "$run-shop" staging 'hostname: staging.shop.example.com' 'env:' ' GREETING: shop staging' +deploy_on "$run-shop" staging +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-shop-staging: deployed" ] || fail "last line: $line" +[ "$(on stat -c '%U %a' "/opt/stacks/$run-shop-staging")" = 'plexus 750' ] || fail "the directory is not the deploy user's, 0750" +[ "$(port_of "$run-shop-staging")" = "$first" ] || fail "the port is $(port_of "$run-shop-staging"), not $first" +[ "$(on cat "/etc/caddy/stacks/$run-shop-staging.caddy")" = "$(printf 'staging.shop.example.com {\n\timport stack %s\n}' "$first")" ] || + fail "the fragment: $(on cat "/etc/caddy/stacks/$run-shop-staging.caddy")" +[ "$(get staging.shop.example.com /)" = 'shop staging 200' ] || fail "the route: $(get staging.shop.example.com /)" +[ "$(get staging.shop.example.com /healthz)" = ' 403' ] || fail "/healthz from outside: $(get staging.shop.example.com /healthz)" +echo "✓ $case" + +case='a run in which nothing changed reloads nothing' +before=$(files) reloaded=$(reloads) +web_id=$(docker ps -q --filter "label=com.docker.compose.project=$run-shop-staging") +deploy_on "$run-shop" staging +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-shop-staging: unchanged" ] || fail "last line: $line" +! grep -q 'changed=[1-9]' "$work/out" || fail "a task reported a change" +[ "$(files)" = "$before" ] || fail "a file changed" +[ "$(reloads)" = "$reloaded" ] || fail "the proxy was reloaded" +[ "$(docker ps -q --filter "label=com.docker.compose.project=$run-shop-staging")" = "$web_id" ] || fail "web was re-created" +echo "✓ $case" + +case='two first deploys started at once end with different ports' +site "$run-shop" production 'hostname: shop.example.com' 'env:' ' GREETING: shop production' +site "$run-docs" production 'hostname: docs.example.com' 'env:' ' GREETING: docs production' +play_on "$work/out-shop" "$run-shop" production & +shop=$! +play_on "$work/out-docs" "$run-docs" production & +docs=$! +shop_status=0 docs_status=0 +wait "$shop" || shop_status=$? +wait "$docs" || docs_status=$? +cat "$work/out-shop" "$work/out-docs" >"$work/out" +[ "$shop_status $docs_status" = '0 0' ] || fail "exit codes $shop_status and $docs_status" +ports="$(port_of "$run-shop-production") $(port_of "$run-docs-production")" +[ "$ports" = "$((first + 1)) $((first + 2))" ] || [ "$ports" = "$((first + 2)) $((first + 1))" ] || fail "the ports are $ports" +[ "$(get shop.example.com /)" = 'shop production 200' ] || fail "shop's route: $(get shop.example.com /)" +[ "$(get docs.example.com /)" = 'docs production 200' ] || fail "docs' route: $(get docs.example.com /)" +echo "✓ $case" + +case='a hostname that another environment serves' +site "$run-shop" preview 'hostname: Staging.Shop.example.com' 'env:' ' GREETING: shop preview' +deploy_on "$run-shop" preview +[ "$status" != 0 ] || fail "exit code 0" +[[ $line == "$run-shop-preview: failed: "*"staging.shop.example.com is the hostname of $run-shop-staging on this host"* ]] || + fail "last line: $line" +on test ! -e "/etc/caddy/stacks/$run-shop-preview.caddy" || fail "a fragment was written" +on test ! -e "/opt/stacks/$run-shop-preview" || fail "the directory was laid out" +[ "$(get staging.shop.example.com /)" = 'shop staging 200' ] || fail "the route of staging: $(get staging.shop.example.com /)" +echo "✓ $case" + +case='a changed value that breaks the healthcheck, its route kept' +env_before=$(on cat "/opt/stacks/$run-shop-staging/.env") +fragment_before=$(on cat "/etc/caddy/stacks/$run-shop-staging.caddy") +site "$run-shop" staging 'hostname: staging.shop.example.com' 'env:' ' GREETING: shop staging, changed' ' HEALTH: bad' +deploy_on "$run-shop" staging +[ "$status" != 0 ] || fail "exit code 0" +[[ $line == "$run-shop-staging: rolled back: "*unhealthy* ]] || fail "last line: $line" +[ "$(on cat "/opt/stacks/$run-shop-staging/.env")" = "$env_before" ] || fail ".env is not the one before" +[ "$(on cat "/etc/caddy/stacks/$run-shop-staging.caddy")" = "$fragment_before" ] || fail "the fragment changed" +[ "$(get staging.shop.example.com /)" = 'shop staging 200' ] || fail "the route: $(get staging.shop.example.com /)" +echo "✓ $case" + +case='a port that a directory holds is kept, outside the range too' +as_deploy sh -c "mkdir /opt/stacks/$run-docs-legacy && + printf 'COMPOSE_PROJECT_NAME=$run-docs-legacy\nPLEXUS_LOOPBACK_PORT=$legacy\n' >/opt/stacks/$run-docs-legacy/.env" +site "$run-docs" legacy 'hostname: legacy.docs.example.com' 'env:' ' GREETING: docs legacy' +deploy_on "$run-docs" legacy +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-docs-legacy: deployed" ] || fail "last line: $line" +[ "$(port_of "$run-docs-legacy")" = "$legacy" ] || fail "the port is $(port_of "$run-docs-legacy"), not $legacy" +[ "$(get legacy.docs.example.com /)" = 'docs legacy 200' ] || fail "the route: $(get legacy.docs.example.com /)" +echo "✓ $case" + +case='no free port' +site "$run-docs" qa 'hostname: qa.docs.example.com' 'env:' ' GREETING: docs qa' +deploy_on "$run-docs" qa -e stack_port_range="$first-$first" +[ "$status" != 0 ] || fail "exit code 0" +[[ $line == "$run-docs-qa: failed: "*"no port from $first to $first is free"* ]] || fail "last line: $line" +on test ! -e "/etc/caddy/stacks/$run-docs-qa.caddy" || fail "a fragment was written" +echo "✓ $case" + +case='a route the proxy refuses' +printf 'broken.example.com {\n' | docker exec -i -u plexus "$host" sh -c "cat >/etc/caddy/stacks/$run-broken.caddy" +site "$run-docs" preview 'hostname: preview.docs.example.com' 'env:' ' GREETING: docs preview' +deploy_on "$run-docs" preview +[ "$status" != 0 ] || fail "exit code 0" +[[ $line == "$run-docs-preview: failed: "*"the proxy refused the route of preview.docs.example.com"* ]] || fail "last line: $line" +on test ! -e "/etc/caddy/stacks/$run-docs-preview.caddy" || fail "the refused fragment is still there" +as_deploy rm "/etc/caddy/stacks/$run-broken.caddy" +as_deploy sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload once the broken fragment is gone" +echo "✓ $case" + +case='a dry run of a new environment with a hostname' +site "$run-docs" beta 'hostname: beta.docs.example.com' 'env:' ' GREETING: docs beta' +before=$(files) reloaded=$(reloads) +deploy_on "$run-docs" beta --check --diff +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-docs-beta: would deploy" ] || fail "last line: $line" +[ "$(files)" = "$before" ] || fail "a file changed" +[ "$(reloads)" = "$reloaded" ] || fail "the proxy was reloaded" +echo "✓ $case" From 10b03659fac6251d28361f42672b2ca6a67b1db7 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:18:28 +0100 Subject: [PATCH 58/91] The stack playbook claims an environment's port and writes its route Where the environment has a hostname, files/route.sh runs on the host under one lock file under /opt/stacks, which a second deploy waits for: it refuses a hostname another environment's fragment serves, keeps the port the environment's .env names or takes the lowest of stack_port_range (20000-20999) that no other .env and no other fragment names, and writes the route fragment and reloads the proxy only where the fragment's text changes, putting back what was there where the proxy refuses. .env carries the port as PLEXUS_LOOPBACK_PORT. A rollback restores the files and leaves the route, which joins the hostname to a port that does not change. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/playbooks/stack.yml | 73 ++++++++++++------- .../platform/roles/stack/defaults/main.yml | 4 + ansible/platform/roles/stack/files/route.sh | 71 ++++++++++++++++++ ansible/platform/roles/stack/tasks/main.yml | 36 +++++++-- 4 files changed, 148 insertions(+), 36 deletions(-) create mode 100755 ansible/platform/roles/stack/files/route.sh diff --git a/ansible/platform/playbooks/stack.yml b/ansible/platform/playbooks/stack.yml index 43d8a58d..cf5efcbc 100644 --- a/ansible/platform/playbooks/stack.yml +++ b/ansible/platform/playbooks/stack.yml @@ -11,18 +11,21 @@ # Variables, documented in the role's defaults: stack_name, # stack_environment_file and stack_compose_file, given on every run; the # environment is named after its file (staging.yaml is staging). Further -# stack_root (/opt/stacks) and stack_wait_timeout (60 seconds). It takes no -# inventory: the one host is the file's `host`, [user@]address[:port], reached -# as the user it names, else as plexus_deploy_user (the role deploy_user's -# default, plexus), on the port it names, else 22. Arguments of -# ansible-playbook for the connection, such as --ssh-common-args or -# --private-key, apply to it. +# stack_root (/opt/stacks), stack_port_range (20000-20999) and +# stack_wait_timeout (60 seconds). It takes no inventory: the one host is the +# file's `host`, [user@]address[:port], reached as the user it names, else as +# plexus_deploy_user (the role deploy_user's default, plexus), on the port it +# names, else 22. Arguments of ansible-playbook for the connection, such as +# --ssh-common-args or --private-key, apply to it. # # What it expects where it runs: the vault's CLI, op, with a session or a # token, where the environment has secrets. On the host, as the platform # playbook prepares it (PLX-Stack/PreparedHost): the deploy user, owner of -# /opt/stacks; Docker with its compose plugin, which that user may run (the -# docker group); and Python. It uses no privilege escalation. +# /opt/stacks; where the environment has a hostname, the directory of route +# fragments the deploy user writes and the sudo rule by which it reloads the +# proxy (both as the header of the ingress role's tasks names them); Docker +# with its compose plugin, which that user may run (the docker group); and +# Python. It uses no privilege escalation but that rule. # # In order, where it runs: # 1. Checks its variables, and reads the environment's file and checks that @@ -33,22 +36,32 @@ # and adds the host the file names. # On the host, into /opt/stacks/-, the compose project of # that name: -# 3. Creates the directory where it is missing, mode 0750. -# 4. Renders .env from `env`, with COMPOSE_PROJECT_NAME; .env.secret, mode +# 3. Where the environment has a hostname, under the lock /opt/stacks/.lock, +# which a second run waits for (up to 300 seconds): refuses the hostname +# where another environment's route fragment serves it; takes the +# environment's loopback port, the one its .env holds, else the lowest of +# stack_port_range that neither another directory's .env nor another +# fragment names, so that it is kept for good; writes the fragment +# -.caddy where its text changes, and reloads the +# proxy then. Where the proxy refuses the reload, it puts the fragment +# back as it was and fails. (The role's files/route.sh.) +# 4. Creates the directory where it is missing, mode 0750. +# 5. Renders .env from `env`, with COMPOSE_PROJECT_NAME and, where the +# environment has a hostname, PLEXUS_LOOPBACK_PORT; .env.secret, mode # 0600, from the secrets' values, where the environment has secrets or # the directory holds one already; each value double-quoted and escaped # (templates/dotenv.j2), so that Compose reads it back as written. # Compares them, and the compose file, with the files in place: a file # that changes is kept as .prev, all of them before the first is # written, and then written, .env, .env.secret, compose.yaml. -# 5. Pulls the images, where compose.yaml changed, so that an image that +# 6. Pulls the images, where compose.yaml changed, so that an image that # cannot be had fails the deploy before migrate runs, and a tag that moved # since the last deploy is fetched, which run and up, pulling only what is # missing, would not do. -# 6. Runs the service `migrate` once, where compose.yaml changed and has +# 7. Runs the service `migrate` once, where compose.yaml changed and has # one, and removes its container; where it fails, the line says its exit # code and the last line it wrote. -# 7. Brings up every service Compose starts by itself, `migrate` excepted, with +# 8. Brings up every service Compose starts by itself, `migrate` excepted, with # --no-deps, so that a service that depends on migrate's completion does # not run it again, and --remove-orphans, so that a service the file no # longer has goes. Then waits for every service that declares a @@ -62,28 +75,30 @@ # `migrate` alone or of none, it starts nothing and takes down whatever # the project still runs; a take-down of something it ran counts as # deployed, as a start does. -# A failure after the first write of 4 restores the files that run replaced, -# each from its .prev, removes a file it created, and runs 7 again. Where -# compose.yaml was not there before, a first deploy, it removes the stack's -# containers and networks and the compose.yaml instead; the volumes, .env and -# .env.secret stay. Where no file changed, a failure undoes nothing; so a run -# after a rollback, with the same files, deploys them again and fails the same -# way. A run in which nothing changed changes no file and re-creates no +# A failure after the first write of 5 restores the files that run replaced, +# each from its .prev, removes a file it created, and runs 8 again; the route +# is not rolled back, since it joins the hostname to a port that does not +# change. Where compose.yaml was not there before, a first deploy, it removes +# the stack's containers and networks and the compose.yaml instead; the +# volumes stay, and .env and .env.secret stay with the port the route names. +# Where no file changed, a failure undoes nothing; so a run after a rollback, +# with the same files, deploys them again and fails the same way. A run in +# which nothing changed changes no file, reloads nothing and re-creates no # container. # # Nothing locks an environment as a whole: two runs for the same environment # at the same time are not supported, and can both fail, one undoing what the # other made. What keeps them apart is the pipeline's own order, one deploy job -# per branch at a time. +# per branch at a time. The lock of 3 keeps two environments from one port. # # No secret's value appears in the run's output, with -v or --diff either: # every task that holds one prints nothing of it. # # The last task, Result, prints one line as its `msg`: -# -: deployed a file changed, or a container was started or -# taken down; healthy +# -: deployed a file or the route changed, or a container was +# started or taken down; healthy # -: unchanged nothing changed, and healthy -# -: would deploy under --check, where a file would change +# -: would deploy under --check, where a file or the route would change # -: rolled back: the previous files are up and healthy again # -: failed: nothing was rolled back, or the undo failed too # names the step that failed and the first line of its error, as in @@ -92,10 +107,10 @@ # variables fails, the line begins `the stack:`. The task, and with it the # run, fails unless the line says deployed, unchanged or would deploy. # -# --check, with --diff, runs 1 to 4 and shows whether .env, .env.secret and -# compose.yaml would change, and how, but for .env.secret. It writes nothing, -# and pulls, migrates and starts nothing, so it says nothing about the images, -# migrate or health. +# --check, with --diff, runs 1 to 5 and shows whether .env, .env.secret, +# compose.yaml and the route would change, and how, but for .env.secret. It +# writes nothing, takes no lock, and pulls, migrates and starts nothing, so it +# says nothing about the images, migrate or health. - name: Read the environment hosts: localhost connection: local @@ -111,5 +126,7 @@ - name: Deploy one environment of a stack hosts: stack_host gather_facts: false + vars_files: + - ../roles/ingress/defaults/main.yml # ingress_fragments_dir roles: - { role: plexus.platform.stack } diff --git a/ansible/platform/roles/stack/defaults/main.yml b/ansible/platform/roles/stack/defaults/main.yml index e2489a03..b52e972a 100644 --- a/ansible/platform/roles/stack/defaults/main.yml +++ b/ansible/platform/roles/stack/defaults/main.yml @@ -14,6 +14,10 @@ # (PLX-Stack/HostDirectory; the role deploy_user gives the deploy user the same path). stack_root: /opt/stacks +# The ports an environment's loopback port is taken from, -: the +# lowest that no other environment on the host holds, taken once and kept. +stack_port_range: 20000-20999 + # How long, in seconds, the deploy waits for every service that declares a # healthcheck to turn healthy: the whole wait, which a healthcheck's # start_period does not extend. diff --git a/ansible/platform/roles/stack/files/route.sh b/ansible/platform/roles/stack/files/route.sh new file mode 100755 index 00000000..f3b15463 --- /dev/null +++ b/ansible/platform/roles/stack/files/route.sh @@ -0,0 +1,71 @@ +#!/bin/sh +# The port and the route of one environment, run on the host as the deploy +# user by the stack role (tasks/main.yml), where the environment has a +# hostname. Under the lock /.lock, which a second run waits for, it +# 1. refuses the hostname where the route fragment of another environment +# serves it; +# 2. takes the environment's loopback port from its .env, and where that +# names none, the lowest port of the range that neither another +# directory's .env nor another environment's fragment names; +# 3. writes the fragment /.caddy where its text changes, +# and reloads the proxy through the deploy user's one sudo rule; where the +# proxy refuses the reload, it puts back what was there. +# It prints `port= route=changed|unchanged`, or why it refuses, and then +# exits 1. With `check` last it takes no lock, writes and reloads nothing, and +# prints what it would do. The fragment's shape and the reload rule are the +# ingress role's (the header of its tasks/main.yml). +# +# route.sh - [check] +set -eu +root=$1 fragments=$2 project=$3 hostname=$4 first=${5%-*} last=${5#*-} check=${6:-} +fragment=$fragments/$project.caddy + +if [ "$check" != check ]; then + exec 9>>"$root/.lock" + flock -w 300 9 || { echo "$root/.lock is held by another deploy and was not released within 300 seconds"; exit 1; } +fi + +# The hostnames a fragment serves: the addresses before its first `{`, without +# a scheme or a port. +served() { + sed -n '1{s/{.*//;s/,/ /g;p;}' "$1" | tr '[:upper:]' '[:lower:]' | tr -s ' \t' '\n' | sed 's|^[a-z]*://||;s|:[0-9]*$||' +} +for other in "$fragments"/*.caddy; do + [ -f "$other" ] && [ "$other" != "$fragment" ] || continue + if served "$other" | grep -qxF "$hostname"; then + echo "$hostname is the hostname of $(basename "$other" .caddy) on this host, whose route $other serves it" + exit 1 + fi +done + +port_in() { sed -n "s/^PLEXUS_LOOPBACK_PORT=[\"']\{0,1\}\([0-9][0-9]*\).*/\1/p" "$1" 2>/dev/null | tail -1; } +port=$(port_in "$root/$project/.env") +if [ -z "$port" ]; then + taken=" " + for env in "$root"/*/.env; do + [ -f "$env" ] && [ "$env" != "$root/$project/.env" ] && taken="$taken$(port_in "$env") " + done + for other in "$fragments"/*.caddy; do + [ -f "$other" ] && [ "$other" != "$fragment" ] && + taken="$taken$(sed -n 's/^[[:space:]]*import stack \([0-9][0-9]*\).*/\1/p' "$other" | tr '\n' ' ')" + done + port=$first + while case "$taken" in *" $port "*) true ;; *) false ;; esac; do port=$((port + 1)); done + [ "$port" -le "$last" ] || { echo "no port from $first to $last is free on this host for $project"; exit 1; } +fi + +text=$(printf '%s {\n\timport stack %s\n}' "$hostname" "$port") +if [ -f "$fragment" ] && [ "$(cat "$fragment")" = "$text" ]; then + echo "port=$port route=unchanged" + exit 0 +fi +if [ "$check" != check ]; then + previous=$(cat "$fragment" 2>/dev/null) && had=1 || had=0 + printf '%s\n' "$text" >"$fragment.new" && mv "$fragment.new" "$fragment" + if ! said=$(sudo -n /usr/bin/systemctl reload caddy 2>&1); then + if [ "$had" = 1 ]; then printf '%s\n' "$previous" >"$fragment.new" && mv "$fragment.new" "$fragment"; else rm -f "$fragment"; fi + echo "the proxy refused the route of $hostname, which is as it was; caddy validate on the host says why: $(printf '%s' "$said" | head -1)" + exit 1 + fi +fi +echo "port=$port route=changed" diff --git a/ansible/platform/roles/stack/tasks/main.yml b/ansible/platform/roles/stack/tasks/main.yml index d3c9b91e..e4bfa76f 100644 --- a/ansible/platform/roles/stack/tasks/main.yml +++ b/ansible/platform/roles/stack/tasks/main.yml @@ -1,5 +1,5 @@ --- -# Steps 3 to 7 of the playbook's header, on the environment's host as the +# Steps 3 to 8 of the playbook's header, on the environment's host as the # deploy user; tasks/environment.yml has read the environment before. - name: Deploy, and roll back what a failure after the first write leaves block: @@ -24,20 +24,38 @@ {{ stack_root }} is not there, or not the deploy user's; the platform playbook prepares a host for stacks quiet: true + - name: Claim the port and write the route + when: stack_hostname | length > 0 + ansible.builtin.script: + cmd: >- + route.sh {{ stack_root | quote }} {{ ingress_fragments_dir | quote }} {{ stack_project }} {{ stack_hostname }} + {{ stack_port_range | quote }} {{ 'check' if ansible_check_mode else '' }} + register: stack_route + changed_when: "'route=changed' in stack_route.stdout" + failed_when: false + check_mode: false + + - name: Check that the route was claimed + when: stack_route is not skipped and stack_route.rc != 0 + ansible.builtin.fail: + msg: "{{ (stack_route.stdout_lines + stack_route.stderr_lines) | first | default(stack_route.msg) }}" + - name: Lay out the environment's directory ansible.builtin.file: path: "{{ stack_dir }}" state: directory mode: "0750" - # COMPOSE_PROJECT_NAME is one of the names PLATFORM_VARIABLES lists - # (packages/lib/src/environments.ts). + # COMPOSE_PROJECT_NAME and PLEXUS_LOOPBACK_PORT are two of the names + # PLATFORM_VARIABLES lists (packages/lib/src/environments.ts). - name: Render .env and read the compose file ansible.builtin.set_fact: stack_text: "{{ lookup('ansible.builtin.file', stack_compose, rstrip=false) }}" stack_env_text: >- - {{ lookup('ansible.builtin.template', 'dotenv.j2', - template_vars={'variables': stack_env | combine({'COMPOSE_PROJECT_NAME': stack_project})}) }} + {{ lookup('ansible.builtin.template', 'dotenv.j2', template_vars={'variables': stack_env + | combine({'COMPOSE_PROJECT_NAME': stack_project}) + | combine({'PLEXUS_LOOPBACK_PORT': stack_route.stdout | regex_findall('port=([0-9]+)') | first} + if stack_route is not skipped else {})}) }} - name: Render .env.secret ansible.builtin.set_fact: @@ -157,8 +175,9 @@ - name: Note that the environment is deployed ansible.builtin.set_fact: stack_outcome: >- - {{ ('would deploy' if stack_replaced else 'unchanged') if ansible_check_mode - else ('deployed' if stack_replaced or stack_up is changed or stack_down is changed else 'unchanged') }} + {{ ('would deploy' if stack_replaced or stack_route is changed else 'unchanged') if ansible_check_mode + else ('deployed' if stack_replaced or stack_route is changed or stack_up is changed or stack_down is changed + else 'unchanged') }} rescue: - name: Note why the deploy failed @@ -171,7 +190,8 @@ # Where compose.yaml was there before, back to the files it ran with: each # file the run replaced from its previous copy, and one it created removed. # After a first deploy, to no compose.yaml: its containers and networks go, - # its volumes stay, and so do .env and .env.secret. + # its volumes stay, and .env and .env.secret stay with the port the route + # names. - name: Undo the writes when: stack_written | default([]) | length > 0 block: From 2fe7d023d784802e14ba581d3f1f3d1caf621862 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:29:57 +0100 Subject: [PATCH 59/91] The doctor's test no longer cites the removed requirement PathPrefix or a released name as a citation The maintainer removed path prefixes: a deviation under PLX-Stack/PathPrefix has no meaning the index of an older version could still give it, so the test of released names holds only the renamed one, spelled at run time. Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.test.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 097a4547..43acaeaf 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -2788,17 +2788,16 @@ test('a cyclic alias in compose.yaml is reported as a compose file that cannot b assert.match(found[0]?.problem ?? '', /aliases form a cycle/); }); -test('a deviation under a name released in an earlier version is told what it is now, or that it is gone', () => { - const stale = new Set([...KNOWN, 'PLX-Stack/NoCommittedValues', 'PLX-Stack/PathPrefix']); +test('a deviation under a name released in an earlier version is told what it is now', () => { + // Joined at run time, as the old name must not read as a citation of the compendium's. const old = ['PLX-Stack', 'NoCommittedValues'].join('/'); - const gone = ['PLX-Stack', 'PathPrefix'].join('/'); - const found = diagnose([stack('stateless', {}, [old, gone])], stale).units[0]?.findings; + const stale = new Set([...KNOWN, old]); + const found = diagnose([stack('stateless', {}, [old])], stale).units[0]?.findings; assert.deepEqual(found, [ { requirement: old, problem: 'listed under `deviations`, but no requirement has this name: it is now `PLX-Stack/NoCommittedSecrets`', }, - { requirement: gone, problem: 'listed under `deviations`, but no requirement has this name' }, ]); // The old name silences nothing: the check of the new name still runs. const tracked = repo({ From c37e34541f0c90c2c5ba9730547f52a611ce7456 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:30:43 +0100 Subject: [PATCH 60/91] The doctor no longer lists PLX-Stack/PathPrefix as a removed requirement Path prefixes are gone by the maintainer's decision; the requirement's name stays in the index of the last version until the next one is cut, and nothing here cites it. Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index cac85802..8adf1e53 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -703,9 +703,6 @@ const MOVED_TO_STACK = new Set([ /** What a requirement that was renamed as it moved is called now. */ const RENAMED_ON_MOVE: Readonly> = { NoCommittedValues: 'NoCommittedSecrets' }; -/** Requirements of a version the index of this plx still holds that the compendium no longer has: a deviation under them is unknown whatever the index says. */ -const REMOVED = new Set(['PLX-Stack/PathPrefix']); - /** What a released `PLX-Stack/…` name is called now, where it was renamed; the `PLX-App/…` form is `movedTo`'s. */ function renamedInStack(name: string): string | undefined { const rest = name.startsWith('PLX-Stack/') ? name.slice('PLX-Stack/'.length) : undefined; @@ -801,7 +798,7 @@ function diagnoseUnit(unit: Facts, known: Set): UnitReport { requirement: name, problem: `listed under \`deviations\`, but no requirement has this name: it is now \`${renamedInStack(name)}\``, }); - else if (!known.has(name) || REMOVED.has(name)) + else if (!known.has(name)) findings.push({ requirement: name, problem: 'listed under `deviations`, but no requirement has this name' }); else if (!reasonGiven(declaration?.body ?? '', name)) findings.push({ From 62972fee052e6a3a12a8c193a3a1f59afb69ed66 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:33:50 +0100 Subject: [PATCH 61/91] The deploy verb's test deploys the stacks that have the environment's file, with no inventory Each stack's file for an environment names its host; the playbook is handed the file and no inventory, user, port or environment name, an environment file with a problem refuses the run before any host, and --inventory is an unknown option. Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/deploy.test.ts | 175 +++++++++++------------ 1 file changed, 87 insertions(+), 88 deletions(-) diff --git a/packages/cli/src/commands/deploy.test.ts b/packages/cli/src/commands/deploy.test.ts index db8f4baa..c84527cc 100644 --- a/packages/cli/src/commands/deploy.test.ts +++ b/packages/cli/src/commands/deploy.test.ts @@ -72,7 +72,7 @@ exit 1 * the Result's. */ const ANSIBLE = `printf '%s\\n' "$*" >> "$FAKE/ansible.log" -check= syntax= name= environment= file= last= +check= syntax= name= envfile= file= last= for a in "$@"; do case "$a" in --syntax-check) syntax=1 ;; @@ -80,7 +80,7 @@ for a in "$@"; do esac case "$last$a" in -estack_name=*) name=\${a#stack_name=} ;; - -estack_environment=*) environment=\${a#stack_environment=} ;; + -estack_environment_file=*) envfile=\${a#stack_environment_file=} ;; -estack_compose_file=*) file=\${a#stack_compose_file=} ;; esac last=$a @@ -95,8 +95,10 @@ if [ -n "$syntax" ]; then echo "playbook: plexus.platform.stack" exit 0 fi +environment=$(basename "$envfile" .yaml) project=$name-$environment cat "$file" > "$FAKE/$project.yaml" +cat "$envfile" > "$FAKE/$project.environment.yaml" echo "PLAY [Deploy one environment of a stack] ****" echo "TASK [plexus.platform.stack : Check the variables] ($project) ****" : > "$FAKE/running.$name" @@ -170,19 +172,20 @@ const stack = (name: string, compose: string) => ({ [`stacks/${name}/PLEXUS.md`]: '---\nprofile: stateless\n---\n', [`stacks/${name}/compose.yaml`]: compose, }); -const record = (target: string | undefined, ...stacks: string[]) => - `${target ? `plexus_deploy_target: ${target}\n` : ''}plexus_apps:\n${stacks.map((s) => ` - name: ${s}\n environment: staging\n`).join('')}`; +/** The file of an environment of a stack, in its directory: the host it deploys to, as the file says it. */ +const environment = (stackName: string, name: string, host: string, more = '') => ({ + [`stacks/${stackName}/${name}.yaml`]: `host: ${host}\n${more}`, +}); interface Fixture { root: string; repo: string; - inv: string; fake: string; } /** - * A checkout with the apps shop and admin and the stacks shop, admin and docs, which has no app; an inventory with - * records in staging for all three, shop and admin on one host, docs on another reached on its own port. + * A checkout with the apps shop and admin and the stacks shop, admin and docs, which has no app; a file for staging + * in each, shop and admin on one host, docs on another as a user of its own and on its own port. */ function fixture(): Fixture { const root = mkdtempSync(join(scratch, 'case-')); @@ -194,13 +197,11 @@ function fixture(): Fixture { ...stack('shop', SHOP_COMPOSE), ...stack('admin', ADMIN_COMPOSE), ...stack('docs', DOCS_COMPOSE), + ...environment('shop', 'staging', 'a.example.com'), + ...environment('admin', 'staging', 'a.example.com'), + ...environment('docs', 'staging', 'deploy@b.example.com:2222'), }); - const inv = join(root, 'inv'); - put(inv, { - 'host_vars/a.yml': record('ssh://deploy@a.example.com', 'shop', 'admin'), - 'host_vars/b.yml': record('ssh://deploy@b.example.com:2222', 'docs'), - }); - return { root, repo, inv, fake: fakes(root) }; + return { root, repo, fake: fakes(root) }; } /** What the last `plx` wrote, whether it ended or threw. */ @@ -236,19 +237,8 @@ async function plx(args: string[], fake: string, env: Record = { return wrote.err; } -/** `plx deploy` for staging in the fixture's checkout with its inventory, with more arguments. */ -const staging = (f: Fixture, ...more: string[]) => [ - 'deploy', - '-e', - 'staging', - '--inventory', - f.inv, - '--commit', - SHA, - '-C', - f.repo, - ...more, -]; +/** `plx deploy` for staging in the fixture's checkout, with more arguments. */ +const staging = (f: Fixture, ...more: string[]) => ['deploy', '-e', 'staging', '--commit', SHA, '-C', f.repo, ...more]; /** The calls of the stack playbook that deployed, one line each, without the check that it is installed. */ const runs = (fake: string): string[] => @@ -289,27 +279,28 @@ test('plx deploy renders each stack with every app image pinned by the digest it ]); }); -test('plx deploy runs the stack playbook once per stack against the host of its record, all stacks at once, and ends with one line per stack', async () => { +test('plx deploy runs the stack playbook once per stack with the environment file of the stack, all stacks at once, and ends with one line per stack', async () => { const f = fixture(); writeFileSync(join(f.fake, 'together'), 'shop\nadmin\ndocs\n'); const err = await plx(staging(f), f.fake); const calls = runs(f.fake); assert.equal(calls.length, 3, calls.join('\n')); const call = (name: string) => calls.find((c) => c.includes(`stack_name=${name} `)) ?? ''; - assert.match( - call('shop'), - /^-i a\.example\.com, -u deploy .*-e stack_name=shop -e stack_environment=staging -e stack_compose_file=\S+ plexus\.platform\.stack$/, + // The host, its user and its port are the file's, which the playbook reads: no inventory, no user, no environment name. + assert.equal( + call('shop').replace(/stack_compose_file=\S+/, 'stack_compose_file='), + `--ssh-common-args -o StrictHostKeyChecking=accept-new -e stack_name=shop -e stack_environment_file=${join(f.repo, 'stacks/shop/staging.yaml')} -e stack_compose_file= plexus.platform.stack`, ); - assert.match(call('docs'), /^-i b\.example\.com, -u deploy -e ansible_port=2222 /); + for (const call of calls) assert.doesNotMatch(call, /(^| )-[iu] |stack_environment=|ansible_port/); assert.doesNotMatch(err, /ran alone/, 'every stack ran while the others did'); // Each run's output is one block under a line naming the stack, its environment and the host, never interleaved. const projects = { 'shop-staging': 'a.example.com', 'admin-staging': 'a.example.com', - 'docs-staging': 'b.example.com:2222', + 'docs-staging': 'deploy@b.example.com:2222', }; for (const [project, host] of Object.entries(projects)) { - const block = err.split(`── ${project} → ssh://deploy@${host} ──\n`)[1]?.split(/^── /m)[0] ?? ''; + const block = err.split(`── ${project} → ${host} ──\n`)[1]?.split(/^── /m)[0] ?? ''; assert.match(block, new RegExp(`\\(${project}\\) \\*+\\nok: \\[host\\] \\(${project}\\)`), err); for (const other of Object.keys(projects).filter((p) => p !== project)) assert.doesNotMatch(block, new RegExp(`\\(${other}\\)`), err); @@ -318,10 +309,9 @@ test('plx deploy runs the stack playbook once per stack against the host of its assert.equal(process.exitCode, undefined); }); -test('plx deploy says what each stack came to: unchanged, rolled back, a run that ended early, no record, no target; one failure fails the run and stops no other', async () => { +test('plx deploy says what each stack came to: unchanged, rolled back, a run that ended early, no file for the environment; one failure fails the run and stops no other', async () => { const f = fixture(); - put(f.repo, { ...stack('blog', DOCS_COMPOSE), ...stack('wiki', DOCS_COMPOSE) }); - put(f.inv, { 'group_vars/platform.yml': record(undefined, 'wiki') }); + put(f.repo, stack('blog', DOCS_COMPOSE)); writeFileSync(join(f.fake, 'outcome.admin'), 'unchanged\n'); writeFileSync( join(f.fake, 'outcome.shop'), @@ -334,12 +324,11 @@ test('plx deploy says what each stack came to: unchanged, rolled back, a run tha const err = await plx(staging(f), f.fake); assert.deepEqual(summary(err), [ '✓ admin-staging: unchanged', - '- blog-staging: no record in staging; not deployed', + '- blog-staging: no staging.yaml; not deployed', '✗ docs-staging: failed: ansible-playbook exited 4: fatal: [b.example.com]: UNREACHABLE! ssh: connect to host b.example.com port 2222: Connection refused', "✗ shop-staging: rolled back: 'Bring the stack up and wait for health' failed (rc 1): General error: container shop-staging-web-1 is unhealthy", - `✗ wiki-staging: its record in ${join(f.inv, 'group_vars/platform.yml')} names no plexus_deploy_target`, ]); - assert.equal(runs(f.fake).length, 3, 'blog and wiki were deployed nowhere'); + assert.equal(runs(f.fake).length, 3, 'blog was deployed nowhere'); assert.equal(process.exitCode, 1); }); @@ -358,16 +347,17 @@ test('a repo whose stacks have zero apps deploys the same way: no image is resol 'PLEXUS.md': '---\ntemplates: [repo-operations]\n---\n', ...stack('docs', DOCS_COMPOSE), ...stack('wiki', DOCS_COMPOSE), - 'inventory/host_vars/b.yml': record('ssh://deploy@b.example.com', 'docs', 'wiki'), + ...environment('docs', 'staging', 'b.example.com'), + ...environment('wiki', 'staging', 'b.example.com'), }); - const err = await plx(['deploy', '-e', 'staging', '--inventory', join(ops, 'inventory'), '-C', ops], f.fake); + const err = await plx(['deploy', '-e', 'staging', '-C', ops], f.fake); assert.deepEqual(summary(err), ['✓ docs-staging: deployed', '✓ wiki-staging: deployed']); assert.equal(existsSync(join(f.fake, 'docker.log')), false); }); test('without --environment the environment follows the branch; where it follows none, the verb says so', async () => { const f = fixture(); - const args = ['deploy', '--inventory', f.inv, '--commit', SHA, '-C', f.repo]; + const args = ['deploy', '--commit', SHA, '-C', f.repo]; await assert.rejects( plx(args, f.fake, { GITHUB_EVENT_NAME: 'pull_request', GITHUB_REF_NAME: '3/merge' }), UsageError, @@ -378,34 +368,27 @@ test('without --environment the environment follows the branch; where it follows assert.equal(summary(err).length, 3); }); -test('plx deploy needs the inventory the records are read from, and says what to pass in the same words in every repo', async () => { +/** `plx` as its own process, which ends as a command line does: its exit code and what it wrote to stderr. */ +function plxProcess(args: string[]): { status: number | null; stderr: string } { + const bin = fileURLToPath(new URL('../bin.ts', import.meta.url)); + const env: NodeJS.ProcessEnv = { ...process.env }; + for (const name of ['GITHUB_EVENT_NAME', 'GITHUB_REF_NAME', 'PLX_DRY_RUN', 'NODE_TEST_CONTEXT']) delete env[name]; + const { status, stderr } = spawnSync(process.execPath, [bin, ...args], { env, encoding: 'utf8' }); + return { status, stderr }; +} + +test('plx deploy has no --inventory: a deploy reads only its own repo, and the flag is an unknown option', () => { const f = fixture(); - const refusal = (e: unknown) => - e instanceof UsageError && - e.message.includes('--inventory /inventory') && - e.message.includes('--inventory inventory'); - let first = ''; - await assert.rejects(plx(['deploy', '-e', 'staging', '-C', f.repo], f.fake), (e: unknown) => { - first = (e as Error).message; - return refusal(e); - }); - const ops = join(f.root, 'operations'); - put(ops, { 'PLEXUS.md': '---\ntemplates: [repo-operations]\n---\n', ...stack('docs', DOCS_COMPOSE) }); - await assert.rejects( - plx(['deploy', '-e', 'staging', '-C', ops], f.fake), - (e: unknown) => refusal(e) && (e as Error).message === first, - ); - await assert.rejects( - plx(['deploy', '-e', 'staging', '--inventory', join(f.root, 'nowhere'), '-C', f.repo], f.fake), - (e: unknown) => e instanceof UsageError && /no inventory directory/.test(e.message), - ); + const { status, stderr } = plxProcess(['deploy', '-e', 'staging', '--inventory', join(f.root, 'inv'), '-C', f.repo]); + assert.equal(status, 2); + assert.match(stderr, /unknown option '--inventory'/); assert.deepEqual(runs(f.fake), []); }); test('a --commit that is not a full hash is one usage error naming it, before any stack is deployed', async () => { const f = fixture(); await assert.rejects( - plx(['deploy', '-e', 'staging', '--inventory', f.inv, '--commit', 'abc1234', '-C', f.repo], f.fake), + plx(['deploy', '-e', 'staging', '--commit', 'abc1234', '-C', f.repo], f.fake), (e: unknown) => e instanceof UsageError && /--commit.*full/.test(e.message), ); assert.deepEqual(runs(f.fake), []); @@ -457,7 +440,7 @@ test('a checkout without a stack is refused, for there is nothing to deploy; a c const f = fixture(); const bare = join(f.root, 'bare'); put(bare, { 'PLEXUS.md': '---\nrepo: shop\n---\n' }); - const args = ['deploy', '-e', 'staging', '--inventory', f.inv, '-C', bare]; + const args = ['deploy', '-e', 'staging', '-C', bare]; await assert.rejects( plx(args, f.fake), (e: unknown) => e instanceof Error && /has no stack to deploy/.test(e.message) && !/apps\//.test(e.message), @@ -479,7 +462,7 @@ test('a checkout without a stack is refused, for there is nothing to deploy; a c assert.deepEqual(runs(f.fake), []); }); -test('where no stack has a record in the environment, each is named, and the run fails, for nothing was deployed; it needs no Ansible', async () => { +test('where no stack has a file for the environment, each is named, and the run fails, for nothing was deployed; it needs no Ansible', async () => { const f = fixture(); const noAnsible = fakes(join(f.root, 'no-ansible'), ['docker']); const err = await plx( @@ -489,25 +472,44 @@ test('where no stack has a record in the environment, each is named, and the run true, ); assert.deepEqual(err.trimEnd().split('\n').slice(-4), [ - '- admin-production: no record in production; not deployed', - '- docs-production: no record in production; not deployed', - '- shop-production: no record in production; not deployed', - '✗ no stack has a record in production: nothing was deployed', + '- admin-production: no production.yaml; not deployed', + '- docs-production: no production.yaml; not deployed', + '- shop-production: no production.yaml; not deployed', + '✗ no stack has a production.yaml: nothing was deployed', ]); assert.equal(process.exitCode, 1); - // One stack with a record: the others are skipped, and no failure. - put(f.inv, { 'host_vars/a.yml': record('ssh://deploy@a.example.com', 'shop') }); - put(f.inv, { 'host_vars/b.yml': 'plexus_apps: []\n' }); + // One stack with a file: the others are skipped, and no failure. + for (const name of ['admin', 'docs']) rmSync(join(f.repo, 'stacks', name, 'staging.yaml')); process.exitCode = undefined; const one = await plx(staging(f), f.fake); assert.deepEqual(summary(one), [ - '- admin-staging: no record in staging; not deployed', - '- docs-staging: no record in staging; not deployed', + '- admin-staging: no staging.yaml; not deployed', + '- docs-staging: no staging.yaml; not deployed', '✓ shop-staging: deployed', ]); assert.equal(process.exitCode, undefined); }); +test('an environment file with a problem refuses the run before any host is reached, naming every problem; another environment’s file is not read', async () => { + const f = fixture(); + put(f.repo, { + ...environment('admin', 'staging', '-oProxyCommand=x'), + ...environment('docs', 'staging', 'b.example.com', 'env: {PORT: 3000}\n'), + ...environment('docs', 'production', '-oProxyCommand=y'), + }); + await assert.rejects( + plx(staging(f), f.fake), + (e: unknown) => + e instanceof UsageError && + e.message.includes('stacks/admin/staging.yaml') && + e.message.includes('stacks/docs/staging.yaml') && + !e.message.includes('production.yaml') && + /no stack was deployed/.test(e.message), + ); + assert.equal(existsSync(join(f.fake, 'ansible.log')), false, 'no playbook ran'); + assert.equal(existsSync(join(f.fake, 'docker.log')), false, 'no registry was read'); +}); + test('in the human mode plx deploy prints no result on stdout, and with --json the result', async () => { const f = fixture(); await plx(staging(f), f.fake); @@ -531,9 +533,9 @@ test('a commit that YAML would read as a number goes in quoted, for PLEXUS_TAG a `services:\n web:\n image: docker.io/acme/docs:1.2.3\n environment:\n RELEASE: \${PLEXUS_TAG}\n COMMIT: \${PLEXUS_COMMIT_SHA:-}\n`, ), ...stack('wiki', DOCS_COMPOSE), - 'inventory/host_vars/b.yml': record('ssh://deploy@b.example.com', 'docs'), + ...environment('docs', 'staging', 'b.example.com'), }); - await plx(['deploy', '-e', 'staging', '--inventory', join(ops, 'inventory'), '--commit', numeric, '-C', ops], f.fake); + await plx(['deploy', '-e', 'staging', '--commit', numeric, '-C', ops], f.fake); assert.equal( readFileSync(join(f.fake, 'docs-staging.yaml'), 'utf8'), `services:\n web:\n image: docker.io/acme/docs:1.2.3\n environment:\n RELEASE: "${numeric}"\n COMMIT: "${numeric}"\n`, @@ -614,8 +616,9 @@ test('a repo whose stack/ its root marker does not name is refused, naming the k 'apps/shop/Dockerfile': 'FROM scratch\n', 'stack/PLEXUS.md': '---\nprofile: stateless\n---\n', 'stack/compose.yaml': SHOP_COMPOSE, + 'stack/staging.yaml': 'host: a.example.com\n', }); - const args = ['deploy', '-e', 'staging', '--inventory', f.inv, '--commit', SHA, '-C', one]; + const args = ['deploy', '-e', 'staging', '--commit', SHA, '-C', one]; await assert.rejects( plx(args, f.fake), (e: unknown) => @@ -643,15 +646,16 @@ test('a repo whose stacks the loader finds a problem with is refused with every assert.equal(existsSync(join(f.fake, 'ansible.log')), false); }); -/** A repo of the stacks docs and wiki, which have no app, and its inventory. */ +/** A repo of the stacks docs and wiki, which have no app, each with a file for staging. */ function operations(f: Fixture): string[] { const ops = join(f.root, 'operations'); put(ops, { ...stack('docs', DOCS_COMPOSE), ...stack('wiki', DOCS_COMPOSE), - 'inventory/host_vars/b.yml': record('ssh://deploy@b.example.com', 'docs', 'wiki'), + ...environment('docs', 'staging', 'b.example.com'), + ...environment('wiki', 'staging', 'b.example.com'), }); - return ['deploy', '-e', 'staging', '--inventory', join(ops, 'inventory'), '-C', ops]; + return ['deploy', '-e', 'staging', '-C', ops]; } test('without ansible-playbook on the PATH the run is refused, saying what to install', async () => { @@ -936,14 +940,9 @@ test('against this machine’s Docker daemon: deployed, unchanged, one service r `, [`stacks/${run}-docs/compose.yaml`]: `services:\n web:\n image: ${docs}\n init: true\n command: ["sleep", "3600"]\n`, }); - const inv = join(root, 'inventory'); - put(inv, { - 'host_vars/localhost.yml': `plexus_deploy_target: ssh://localhost\nplexus_apps:\n${['shop', 'docs'].map((s) => ` - name: ${run}-${s}\n environment: staging\n`).join('')}`, - }); - // Each environment's directory and .env, as the platform playbook lays them out. + // Each stack's file for staging: the host it deploys to, here this machine, and a scratch directory as the root. + for (const s of ['shop', 'docs']) put(repo, { [`stacks/${run}-${s}/staging.yaml`]: 'host: localhost\n' }); const stacks = join(root, 'stacks'); - for (const s of ['shop', 'docs']) - put(stacks, { [`${run}-${s}-staging/.env`]: `COMPOSE_PROJECT_NAME=${run}-${s}-staging\n` }); // The collection of this checkout, alone where Ansible looks; community.docker is the one the ansible package brings. const collections = join(root, 'collections'); mkdirSync(join(collections, 'ansible_collections', 'plexus'), { recursive: true }); @@ -957,7 +956,7 @@ test('against this machine’s Docker daemon: deployed, unchanged, one service r plx( [ ...global, - ...['deploy', '-e', 'staging', '--inventory', inv, '--commit', commit(n), '-C', repo, '--'], + ...['deploy', '-e', 'staging', '--commit', commit(n), '-C', repo, '--'], ...['-c', 'local', '-e', 'ansible_python_interpreter=auto_silent', '-e', `stack_root=${stacks}`], ...['-e', 'stack_wait_timeout=30'], ], From 2381d4177d276abd0bbb90536039d45a5c58beb2 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:39:58 +0100 Subject: [PATCH 62/91] The deploy job's setup test: the deploy key comes from a repository secret, nothing from the vault, no token for a second repo Setup holds the key in an agent, puts op on the PATH for the playbook that reads the secrets, and reads the vault only to join the overlay; --operations-repo is gone. Co-Authored-By: Claude Sonnet 5.5 --- packages/cli-ci/src/commands/setup.test.ts | 176 +++++------------- .../cli-ci/src/commands/setupAppToken.test.ts | 29 +-- packages/cli-ci/src/commands/setupOp.test.ts | 18 +- .../src/commands/setupOperations.test.ts | 90 --------- .../cli-ci/src/commands/setupUsage.test.ts | 15 +- .../src/commands/setupWithoutToken.test.ts | 8 +- 6 files changed, 85 insertions(+), 251 deletions(-) delete mode 100644 packages/cli-ci/src/commands/setupOperations.test.ts diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts index b73ae5e1..4dcc6a8f 100644 --- a/packages/cli-ci/src/commands/setup.test.ts +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -2,7 +2,6 @@ // variables and files, and fakes for the vault's CLI and every other tool on // the PATH (testing/job.ts). import assert from 'node:assert/strict'; -import { createVerify, generateKeyPairSync } from 'node:crypto'; import { readdirSync, readFileSync, statSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { test } from 'node:test'; @@ -53,8 +52,8 @@ test('a Connect server’s address without its token is no Connect server', () = assert.deepEqual(credentialsOf(job.calls), [['OP_SERVICE_ACCOUNT_TOKEN']]); }); -test('with neither, a deploy job fails in one line that names both, and nothing is read', () => { - const job = runJob(['deploy'], { vault: VAULT }); +test('a deploy job that joins the overlay with neither credential fails in one line that names both, and nothing is read', () => { + const job = runJob(['deploy', '--overlay', 'netbird'], { env: { ...DEPLOY_KEY, ...FORGE_RUNNER }, vault: VAULT }); assert.equal(job.status, 1, job.log); assert.deepEqual(credentialsOf(job.calls), []); assert.match(job.log, /OP_CONNECT_HOST and OP_CONNECT_TOKEN/); @@ -132,27 +131,28 @@ test('under --dry-run the vault is read and masked, and nothing is handed or wri const SSH_KEY = [ '-----BEGIN OPENSSH PRIVATE KEY-----', 'b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW', - 'QyNTUxOQAAACDfakefakefakefakefakefakefakefakefakefakefakeAAAA', + 'QyNTUxOQAAACDfakefakefakefakefakefakefakefakefakefakeAAAA', '-----END OPENSSH PRIVATE KEY-----', ].join('\n'); -const SSH_REF = 'op://acme-ci/deploy-ssh/private key?ssh-format=openssh'; -const APP = generateKeyPairSync('rsa', { - modulusLength: 2048, - publicKeyEncoding: { type: 'spki', format: 'pem' }, - privateKeyEncoding: { type: 'pkcs1', format: 'pem' }, -}); -/** The App's client ID: as short and numeric as a port, which the old pipeline's masking found inside a hash. */ -const CLIENT_ID = '587'; - -/** What the vault acme-ci holds for a deploy job. */ -const DEPLOY_VAULT = { - [SSH_REF]: SSH_KEY, - 'op://acme-ci/github-app/client-id': CLIENT_ID, - 'op://acme-ci/github-app/private-key': APP.privateKey.trim(), -}; +/** The deploy key, a repository secret the workflow hands the step. */ +const DEPLOY_KEY = { DEPLOY_SSH_KEY: SSH_KEY }; + +/** The vault's reads a job made. */ +const readsOf = (job: ReturnType) => job.calls.filter((c) => c.tool === 'op' && c.args[0] === 'read'); + +test('a deploy job without the deploy key fails in one line that names it, and starts no agent', () => { + const job = runJob(['deploy'], {}); + assert.equal(job.status, 1, job.log); + assert.match(job.log, /DEPLOY_SSH_KEY/); + assert.equal(job.log.trim().split('\n').length, 1, job.log); + assert.deepEqual( + job.calls.filter((c) => c.tool === 'ssh-add' || c.tool === 'ssh-agent'), + [], + ); +}); -test('a deploy job’s SSH agent holds the deploy key, and the agent’s socket is a variable of the job', () => { - const job = runJob(['deploy'], { env: CONNECT, vault: DEPLOY_VAULT }); +test('a deploy job’s SSH agent holds the deploy key it was handed, and the agent’s socket is a variable of the job', () => { + const job = runJob(['deploy'], { env: DEPLOY_KEY }); assert.equal(job.status, 0, job.log); const socket = join(job.temp, 'ssh-agent.sock'); assert.deepEqual(job.env, { DOCKER_CONFIG: join(job.temp, 'docker'), SSH_AUTH_SOCK: socket }); @@ -160,14 +160,22 @@ test('a deploy job’s SSH agent holds the deploy key, and the agent’s socket const add = job.calls.find((c) => c.tool === 'ssh-add'); assert.deepEqual([add?.args, add?.seen.SSH_AUTH_SOCK, add?.input], [['-'], socket, `${SSH_KEY}\n`]); for (const line of SSH_KEY.split('\n')) assert.ok(masksFirst(job.log).includes(`::add-mask::${line}`), line); - assert.ok( - !job.calls.some((c) => c.tool === 'op' && c.args[1] === KEY_REF), - 'a deploy job reads no server-actions key', +}); + +test('a deploy job reads nothing from the vault, mints no token for a second repo and hands nothing on as an output', () => { + const job = runJob(['deploy'], { env: { ...DEPLOY_KEY, ...CONNECT, ...SERVICE_ACCOUNT }, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.deepEqual(readsOf(job), []); + assert.deepEqual( + job.calls.filter((c) => c.tool === 'curl'), + [], ); + assert.deepEqual(job.output, {}); + assert.doesNotMatch(job.log, /vault|token of the tenant/); }); test('a deploy job is logged in to the forge’s image registry with its own token, which plx deploy reads the digests with', () => { - const job = runJob(['deploy'], { env: CONNECT, vault: DEPLOY_VAULT }); + const job = runJob(['deploy'], { env: DEPLOY_KEY }); assert.equal(job.status, 0, job.log); assert.equal(job.env.DOCKER_CONFIG, join(job.temp, 'docker')); const config = join(job.temp, 'docker', 'config.json'); @@ -181,23 +189,16 @@ test('a deploy job is logged in to the forge’s image registry with its own tok }); test('a key pasted into a one-line field gets its lines back before the agent reads it', () => { - const vault = { ...DEPLOY_VAULT, [SSH_REF]: SSH_KEY.replaceAll('\n', ' ') }; - const job = runJob(['deploy'], { env: CONNECT, vault }); + const job = runJob(['deploy'], { env: { DEPLOY_SSH_KEY: SSH_KEY.replaceAll('\n', ' ') } }); assert.equal(job.status, 0, job.log); assert.equal(job.calls.find((c) => c.tool === 'ssh-add')?.input, `${SSH_KEY}\n`); }); test('with -v, a key pasted into a one-line field shows no line that was not masked before it', () => { - const pasted = (key: string) => key.trim().replaceAll('\n', ' '); - const vault = { - ...DEPLOY_VAULT, - [SSH_REF]: pasted(SSH_KEY), - 'op://acme-ci/github-app/private-key': pasted(APP.privateKey), - }; - const job = runJob(['-v', 'deploy'], { env: CONNECT, vault }); + const job = runJob(['-v', 'deploy'], { env: { DEPLOY_SSH_KEY: SSH_KEY.replaceAll('\n', ' ') } }); assert.equal(job.status, 0, job.log); const lines = job.log.split('\n'); - for (const keyLine of [...SSH_KEY.split('\n'), ...APP.privateKey.trim().split('\n')]) { + for (const keyLine of SSH_KEY.split('\n')) { const masked = lines.indexOf(`::add-mask::${keyLine}`); const shown = lines.findIndex((l) => !l.startsWith('::add-mask::') && l.includes(keyLine)); assert.ok(masked >= 0 && (shown < 0 || masked < shown), `${keyLine} is masked before it is shown`); @@ -208,94 +209,18 @@ test('with -v, a key pasted into a one-line field shows no line that was not mas ); }); -/** The JWT a curl call authorized with, and the request's data. */ -const requestOf = (input = '') => ({ - url: /^url = "(.*)"$/m.exec(input)?.[1], - method: /^request = "(.*)"$/m.exec(input)?.[1], - jwt: /^header = "Authorization: Bearer (.*)"$/m.exec(input)?.[1] ?? '', - data: /^data = (.*)$/m.exec(input)?.[1], -}); - -test('a deploy job is handed a token of the tenant’s App that may read the operations repo, and nothing more', () => { - const job = runJob(['deploy'], { env: SERVICE_ACCOUNT, vault: DEPLOY_VAULT }); - assert.equal(job.status, 0, job.log); - assert.deepEqual(job.output, { 'operations-token': 'ghs_operations' }); - assert.ok(masksFirst(job.log).includes('::add-mask::ghs_operations')); - const [installation, token] = job.calls.filter((c) => c.tool === 'curl').map((c) => requestOf(c.input)); - assert.deepEqual( - [installation?.method, installation?.url], - ['GET', 'https://api.github.com/repos/acme/operations/installation'], - ); - assert.deepEqual( - [token?.method, token?.url, JSON.parse(JSON.parse(token?.data ?? '""'))], - [ - 'POST', - 'https://api.github.com/app/installations/42/access_tokens', - { repositories: ['operations'], permissions: { contents: 'read' } }, - ], - ); - for (const { jwt } of [installation, token]) { - const [header = '', payload = '', signature = ''] = jwt.split('.'); - assert.ok( - createVerify('RSA-SHA256').update(`${header}.${payload}`).verify(APP.publicKey, signature, 'base64url'), - 'signed with the App’s key', - ); - const claims = JSON.parse(Buffer.from(payload, 'base64url').toString()); - assert.equal(claims.iss, CLIENT_ID); - assert.ok(claims.exp - claims.iat <= 600, 'no longer than GitHub allows'); - } -}); - -/** The lines of a job's log that are no mask and name `text`. */ -const linesNaming = (log: string, ...texts: string[]) => - log.split('\n').filter((l) => !l.startsWith('::add-mask::') && texts.every((t) => l.includes(t))); - -test('an App not installed on the operations repo fails the job in one line that names the App and the repo', () => { - const job = runJob(['deploy'], { env: CONNECT, vault: DEPLOY_VAULT, apiStatus: 404 }); - assert.equal(job.status, 1, job.log); - const [line, ...more] = linesNaming(job.log, CLIENT_ID, 'acme/operations'); - assert.deepEqual(more, [], job.log); - assert.match(line ?? '', /not installed/); - assert.doesNotMatch(job.log, /curl -K - exited/); - const { jwt } = requestOf(job.calls.find((c) => c.tool === 'curl')?.input); - assert.deepEqual(linesNaming(job.log, jwt), [], 'the JWT is in no line but its mask'); -}); - -test('a key or client ID GitHub refuses fails the job in one line that names the App and the repo, and tells it from the above', () => { - const job = runJob(['deploy'], { env: CONNECT, vault: DEPLOY_VAULT, apiStatus: 401 }); - assert.equal(job.status, 1, job.log); - const [line, ...more] = linesNaming(job.log, CLIENT_ID, 'acme/operations'); - assert.deepEqual(more, [], job.log); - assert.match(line ?? '', /refused/); - assert.doesNotMatch(line ?? '', /not installed/); - assert.doesNotMatch(job.log, /curl -K - exited/); - const { jwt } = requestOf(job.calls.find((c) => c.tool === 'curl')?.input); - assert.deepEqual(linesNaming(job.log, jwt), [], 'the JWT is in no line but its mask'); -}); - -test('under --dry-run a deploy job reads and masks, and calls nothing: no API, no agent', () => { - const job = runJob(['--dry-run', 'deploy'], { env: CONNECT, vault: DEPLOY_VAULT }); +test('under --dry-run a deploy job masks the deploy key, and starts and writes nothing', () => { + const job = runJob(['--dry-run', 'deploy'], { env: DEPLOY_KEY }); assert.equal(job.status, 0, job.log); + assert.ok(SSH_KEY.split('\n').every((line) => masksFirst(job.log).includes(`::add-mask::${line}`))); assert.deepEqual( job.calls.map((c) => c.tool), - ['op', 'op', 'op', 'op'], - 'the probe for op, then the three reads', + ['op'], + 'the probe for op, and nothing else', ); assert.deepEqual([job.output, job.env], [{}, {}]); }); -test('the operations repo is the one the tenant names', () => { - const job = runJob(['deploy', '--operations-repo', 'ops'], { env: CONNECT, vault: DEPLOY_VAULT }); - assert.equal(job.status, 0, job.log); - assert.match(job.calls.find((c) => c.tool === 'curl')?.input ?? '', /\/repos\/acme\/ops\/installation/); -}); - -test('the App’s client ID is read as no secret and is not masked, as the port of a relay should have been', () => { - const job = runJob(['deploy'], { env: CONNECT, vault: DEPLOY_VAULT }); - assert.equal(job.status, 0, job.log); - assert.ok(!job.log.includes(`::add-mask::${CLIENT_ID}\n`), job.log); -}); - const FORGE_RUNNER = { RUNNER_ENVIRONMENT: 'github-hosted' }; const SLOT = { RUNNER_ENVIRONMENT: 'self-hosted' }; /** The repo names the tenant's cache host, as mise's environment hands it to every step. */ @@ -338,8 +263,8 @@ test('on a slot a job joins nothing and reads no cache token: the slot is on the ['deploy', '--overlay', 'netbird'], ]) { const job = runJob(args, { - env: { ...CONNECT, ...SLOT, ...CACHE_HOST }, - vault: { ...VAULT, ...DEPLOY_VAULT, ...OVERLAY_VAULT }, + env: { ...CONNECT, ...SLOT, ...CACHE_HOST, ...DEPLOY_KEY }, + vault: { ...VAULT, ...OVERLAY_VAULT }, }); assert.equal(job.status, 0, job.log); assert.ok(!job.calls.some((c) => c.tool === 'netbird' || c.tool === 'sudo'), args[0]); @@ -364,8 +289,8 @@ test('on a forge runner, a repo job joins nothing where the repo names no cache test('on a forge runner, a deploy job on netbird joins the overlay and waits for its network map', () => { const job = runJob(['deploy', '--overlay', 'netbird'], { - env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER }, - vault: { ...DEPLOY_VAULT, ...OVERLAY_VAULT }, + env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...DEPLOY_KEY }, + vault: OVERLAY_VAULT, }); assert.equal(job.status, 0, job.log); assert.equal(job.output.joined, 'true'); @@ -387,8 +312,8 @@ test('a repo job whose join fails goes on without the remote cache, and says so test('a deploy job whose join fails fails', () => { const job = runJob(['deploy', '--overlay', 'netbird'], { - env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER }, - vault: { ...DEPLOY_VAULT, ...OVERLAY_VAULT }, + env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...DEPLOY_KEY }, + vault: OVERLAY_VAULT, netbirdFails: true, }); assert.equal(job.status, 1, job.log); @@ -397,8 +322,8 @@ test('a deploy job whose join fails fails', () => { test('a deploy job waits for the network map, never for the cache host its repo names: the cache host is the repo job’s', () => { const job = runJob(['deploy', '--overlay', 'netbird'], { - env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...CACHE_HOST }, - vault: { ...DEPLOY_VAULT, ...OVERLAY_VAULT }, + env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...CACHE_HOST, ...DEPLOY_KEY }, + vault: OVERLAY_VAULT, }); assert.equal(job.status, 0, job.log); assert.equal(job.output.joined, 'true'); @@ -509,8 +434,7 @@ test('a trusted server named without its token is asked nothing and handed no lo test('a deploy job, and a repo job under --dry-run, ask no cache server', () => { const deploy = runJob(['deploy'], { - env: { ...CONNECT, ...SLOT, ...SLOT_CACHES }, - vault: DEPLOY_VAULT, + env: { ...CONNECT, ...SLOT, ...SLOT_CACHES, ...DEPLOY_KEY }, cacheStatus: 200, }); assert.equal(deploy.status, 0, deploy.log); diff --git a/packages/cli-ci/src/commands/setupAppToken.test.ts b/packages/cli-ci/src/commands/setupAppToken.test.ts index 81e463fd..d553b852 100644 --- a/packages/cli-ci/src/commands/setupAppToken.test.ts +++ b/packages/cli-ci/src/commands/setupAppToken.test.ts @@ -197,16 +197,10 @@ for (const job of ['changeset', 'update'] as const) }); test('the calls to the forge’s API see neither the App’s key nor the vault’s credentials', () => { - const deployVault = { - ...VAULT, - 'op://acme-ci/deploy-ssh/private key?ssh-format=openssh': - '-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----', - }; for (const [args, env, vault] of [ [['changeset'], { ...FORGE_APP, ...CONNECT, ...SERVICE_ACCOUNT }, {}], [['update'], { ...CONNECT, ...SERVICE_ACCOUNT }, VAULT], [['update'], { GH_PRIVATE_KEY: APP.privateKey, ...SERVICE_ACCOUNT }, VAULT], - [['deploy'], { ...CONNECT, ...SERVICE_ACCOUNT }, deployVault], ] as const) { const job = runJob([...args], { env, vault }); assert.equal(job.status, 0, job.log); @@ -228,21 +222,14 @@ test('the calls to the forge’s API give up after 10 s without a connection and } }); -for (const job of ['update', 'deploy'] as const) - test(`${job}: a forge that never answers fails the job in one line that names the App and the repo`, () => { - const vault = { - ...VAULT, - 'op://acme-ci/deploy-ssh/private key?ssh-format=openssh': - '-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----', - }; - const run = runJob([job], { env: job === 'update' ? FORGE_APP : CONNECT, vault, apiHangs: true }); - assert.equal(run.status, 1, run.log); - const repo = job === 'update' ? 'acme/web' : 'acme/operations'; - const [line, ...more] = linesNaming(run.log, CLIENT_ID, repo); - assert.deepEqual(more, [], run.log); - assert.match(line ?? '', /did not answer/); - assert.equal(shown(run.log).filter((l) => !/^the vault /.test(l)).length, 1, run.log); - }); +test('update: a forge that never answers fails the job in one line that names the App and the repo', () => { + const run = runJob(['update'], { env: FORGE_APP, vault: VAULT, apiHangs: true }); + assert.equal(run.status, 1, run.log); + const [line, ...more] = linesNaming(run.log, CLIENT_ID, 'acme/web'); + assert.deepEqual(more, [], run.log); + assert.match(line ?? '', /did not answer/); + assert.equal(shown(run.log).filter((l) => !/^the vault /.test(l)).length, 1, run.log); +}); test('a forge that is down fails the job in one line that names the App and the repo, with curl itself', () => { const job = runJob(['changeset'], { env: { ...FORGE_APP, GITHUB_API_URL: 'http://127.0.0.1:1' }, realCurl: true }); diff --git a/packages/cli-ci/src/commands/setupOp.test.ts b/packages/cli-ci/src/commands/setupOp.test.ts index 40830e06..c2ca6eef 100644 --- a/packages/cli-ci/src/commands/setupOp.test.ts +++ b/packages/cli-ci/src/commands/setupOp.test.ts @@ -12,6 +12,8 @@ import { type Call, runJob } from '../testing/job.ts'; const KEY_REF = 'op://acme-ci/repo_web/server-actions-key'; const VAULT = { [KEY_REF]: 'a-key' }; const SERVICE_ACCOUNT = { OP_SERVICE_ACCOUNT_TOKEN: 'ops_service-account' }; +/** The deploy key, a repository secret the workflow hands the deploy job's step. */ +const DEPLOY_KEY = { DEPLOY_SSH_KEY: '-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----' }; const ARCH = ({ x64: 'amd64', arm64: 'arm64' } as Record)[process.arch]; const ZIP = `https://cache.agilebits.com/dist/1P/op2/pkg/v${OP_VERSION}/op_linux_${ARCH}_v${OP_VERSION}.zip`; const KEY = 'https://downloads.1password.com/linux/keys/1password.asc'; @@ -110,14 +112,22 @@ test('a runner that has op is left as it is: nothing is downloaded, and the vaul assert.ok(!(read?.path ?? '').startsWith(job.temp)); }); -test('a deploy job installs op the same way', () => { - const job = runJob(['deploy'], { env: SERVICE_ACCOUNT, vault: {}, noOp: true }); - assert.equal(job.status, 1, 'the vault holds no deploy key, which is the fake’s to refuse'); +test('a deploy job installs op the same way, with no credential for the vault, and puts it on the PATH for the playbook that reads the secrets', () => { + const job = runJob(['deploy'], { env: DEPLOY_KEY, noOp: true }); + assert.equal(job.status, 0, job.log); assert.deepEqual( downloads(job.calls).map((c) => c.args.at(-1)), [ZIP, KEY], ); - assert.ok(reads(job.calls).every((c) => c.path === join(job.temp, 'op', 'bin', 'op'))); + assert.deepEqual(reads(job.calls), [], 'nothing is read from the vault'); + assert.deepEqual(job.path, [join(job.temp, 'op', 'bin')]); +}); + +test('a deploy job on a runner that has op downloads nothing and changes no PATH', () => { + const job = runJob(['deploy'], { env: DEPLOY_KEY }); + assert.equal(job.status, 0, job.log); + assert.deepEqual(downloads(job.calls), []); + assert.deepEqual(job.path, []); }); test('a job without a token installs nothing, whether or not the runner has op', () => { diff --git a/packages/cli-ci/src/commands/setupOperations.test.ts b/packages/cli-ci/src/commands/setupOperations.test.ts deleted file mode 100644 index c71415b5..00000000 --- a/packages/cli-ci/src/commands/setupOperations.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -// plx-ci setup deploy in the operations repo itself, which deploys the third-party apps under its apps/: prepared as -// an app repo's deploy job is, the deploy key in an SSH agent and the overlay joined on a forge runner, but with no -// token of the tenant's App, since the inventory the deploy reads is in the job's own checkout. A checkout is the -// operations repo where its root marker lists the operations template, as plx tells it, whatever the repo is called. -import assert from 'node:assert/strict'; -import { generateKeyPairSync } from 'node:crypto'; -import { join } from 'node:path'; -import { test } from 'node:test'; -import { runJob } from '../testing/job.ts'; - -const CONNECT = { OP_CONNECT_HOST: 'http://localhost:8080', OP_CONNECT_TOKEN: 'connect-token' }; -const SERVICE_ACCOUNT = { OP_SERVICE_ACCOUNT_TOKEN: 'ops_service-account' }; -/** An operations repo the tenant called infra, which the option --operations-repo does not name. */ -const OPERATIONS = { GITHUB_REPOSITORY: 'acme/infra' }; -const MARKER = '---\ntemplates: [repo-operations]\n---\n'; -const SSH_KEY = [ - '-----BEGIN OPENSSH PRIVATE KEY-----', - 'b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW', - '-----END OPENSSH PRIVATE KEY-----', -].join('\n'); -const VAULT = { - 'op://acme-ci/deploy-ssh/private key?ssh-format=openssh': SSH_KEY, - 'op://acme-ci/netbird/setup-key': 'nb-setup-key-0123456789', - 'op://acme-ci/github-app/client-id': '587', - 'op://acme-ci/github-app/private-key': generateKeyPairSync('rsa', { - modulusLength: 2048, - publicKeyEncoding: { type: 'spki', format: 'pem' }, - privateKeyEncoding: { type: 'pkcs1', format: 'pem' }, - }).privateKey, -}; -const reads = (job: ReturnType) => - job.calls.filter((c) => c.tool === 'op' && c.args[0] === 'read').map((c) => c.args[1]); - -test('a deploy job of the operations repo holds the deploy key in an agent, and reads and mints nothing of the App', () => { - const job = runJob(['deploy'], { env: { ...CONNECT, ...OPERATIONS }, vault: VAULT, marker: MARKER }); - assert.equal(job.status, 0, job.log); - assert.deepEqual(reads(job), ['op://acme-ci/deploy-ssh/private key?ssh-format=openssh']); - assert.deepEqual( - job.calls.filter((c) => c.tool === 'curl'), - [], - ); - assert.deepEqual(job.output, {}); - const socket = join(job.temp, 'ssh-agent.sock'); - assert.deepEqual(job.env, { DOCKER_CONFIG: join(job.temp, 'docker'), SSH_AUTH_SOCK: socket }); - assert.equal(job.calls.find((c) => c.tool === 'ssh-add')?.input, `${SSH_KEY}\n`); -}); - -/** The calls to the forge's API a job made, by method and URL. */ -const asked = (job: ReturnType) => - job.calls.filter((c) => c.tool === 'curl').map((c) => /^url = "(.*)"$/m.exec(c.input ?? '')?.[1]); - -for (const [what, marker] of [ - ['an app repo’s marker', '---\ntemplates: [repo-turbo]\n---\n'], - ['no marker', undefined], - ['a marker that cannot be read', '---\ntemplates: repo-operations\n---\n'], -] as const) - test(`a deploy job of a repo called operations whose checkout has ${what} mints the token for the operations repo, as an app repo’s does`, () => { - const job = runJob(['deploy'], { - env: { ...CONNECT, GITHUB_REPOSITORY: 'acme/operations' }, - vault: VAULT, - ...(marker === undefined ? {} : { marker }), - }); - assert.equal(job.status, 0, job.log); - assert.deepEqual(asked(job), [ - 'https://api.github.com/repos/acme/operations/installation', - 'https://api.github.com/app/installations/42/access_tokens', - ]); - assert.deepEqual(job.output, { 'operations-token': 'ghs_operations' }); - }); - -test('on a forge runner, a deploy job of the operations repo on netbird joins the overlay and waits for its network map', () => { - const job = runJob(['deploy', '--overlay', 'netbird'], { - env: { ...SERVICE_ACCOUNT, ...OPERATIONS, RUNNER_ENVIRONMENT: 'github-hosted' }, - vault: VAULT, - marker: MARKER, - }); - assert.equal(job.status, 0, job.log); - assert.deepEqual(job.output, { joined: 'true' }); - const up = job.calls.find((c) => c.tool === 'netbird' && c.args[0] === 'up'); - assert.deepEqual(up?.args, ['up', '--hostname', 'ci-41-deploy']); - assert.ok(!job.calls.some((c) => c.tool === 'getent'), 'it waits for the map, not for a cache host'); -}); - -test('under --dry-run a deploy job of the operations repo reads and masks the deploy key, and says nothing of a token', () => { - const job = runJob(['--dry-run', 'deploy'], { env: { ...CONNECT, ...OPERATIONS }, vault: VAULT, marker: MARKER }); - assert.equal(job.status, 0, job.log); - assert.deepEqual(reads(job), ['op://acme-ci/deploy-ssh/private key?ssh-format=openssh']); - assert.doesNotMatch(job.log, /token of the tenant’s App/); - assert.deepEqual([job.output, job.env], [{}, {}]); -}); diff --git a/packages/cli-ci/src/commands/setupUsage.test.ts b/packages/cli-ci/src/commands/setupUsage.test.ts index c0df79d2..07fd01df 100644 --- a/packages/cli-ci/src/commands/setupUsage.test.ts +++ b/packages/cli-ci/src/commands/setupUsage.test.ts @@ -10,9 +10,6 @@ for (const [args, belongs] of [ [['deploy', '--publishes', 'npm'], /--publishes is an option of the job repo, not of deploy/], [['changeset', '--publishes', 'images'], /--publishes is an option of the job repo, not of changeset/], [['update', '--publishes', 'github'], /--publishes is an option of the job repo, not of update/], - [['repo', '--operations-repo', 'ops'], /--operations-repo is an option of the job deploy, not of repo/], - [['changeset', '--operations-repo', 'ops'], /--operations-repo is an option of the job deploy, not of changeset/], - [['update', '--operations-repo', 'operations'], /--operations-repo is an option of the job deploy, not of update/], [ ['deploy', '--private-packages'], /--private-packages is an option of the jobs repo, changeset and update, not of deploy/, @@ -27,11 +24,15 @@ for (const [args, belongs] of [ assert.deepEqual([job.output, job.env], [{}, {}]); }); +test('--operations-repo is an option of no job: a deploy reads only its own repo', () => { + const job = runJob(['deploy', '--operations-repo', 'operations'], { env: CONNECT }); + assert.notEqual(job.status, 0, job.log); + assert.match(job.log, /unknown option '--operations-repo'/); + assert.deepEqual(job.calls, []); +}); + test('an option of its own kind, named with its default, is no mistake', () => { - for (const args of [ - ['repo', '--publishes', 'images'], - ['deploy', '--operations-repo', 'operations'], - ]) { + for (const args of [['repo', '--publishes', 'images']]) { const job = runJob(args, { env: CONNECT, vault: { 'op://acme-ci/repo_web/server-actions-key': 'k' }, diff --git a/packages/cli-ci/src/commands/setupWithoutToken.test.ts b/packages/cli-ci/src/commands/setupWithoutToken.test.ts index 500a8b66..b9f239e5 100644 --- a/packages/cli-ci/src/commands/setupWithoutToken.test.ts +++ b/packages/cli-ci/src/commands/setupWithoutToken.test.ts @@ -56,12 +56,14 @@ test('a repo job of the workflow on_commit or on_pr reads nothing where it has n assert.deepEqual(job.output, {}); }); -test('a deploy job with no token fails, since it cannot deploy', () => { +test('a deploy job with no deploy key fails, since it cannot deploy, and needs no token for the vault', () => { const job = runJob(['deploy'], { env: { ...FORGE_RUNNER, ...ON_PUSH }, vault: VAULT }); assert.equal(job.status, 1, job.log); - assert.match(job.log, /OP_CONNECT_HOST and OP_CONNECT_TOKEN/); - assert.match(job.log, /OP_SERVICE_ACCOUNT_TOKEN/); + assert.match(job.log, /DEPLOY_SSH_KEY/); assert.ok(!SAYS.test(job.log), 'it does not go on as a job that deploys nothing'); + const keyed = runJob(['deploy'], { env: { ...FORGE_RUNNER, ...ON_PUSH, DEPLOY_SSH_KEY: 'k' }, vault: VAULT }); + assert.equal(keyed.status, 0, keyed.log); + assert.ok(!SAYS.test(keyed.log), 'a deploy job reads no vault, so has no token to miss'); }); test('a job with a token reads as before and says nothing of the kind', () => { From 2a3eef228a03c535ce6d7310322e20a44a318658 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:40:10 +0100 Subject: [PATCH 63/91] The workflows' tests: a deploy job checks out its own repo alone and holds the two repository secrets of a deploy The step of plx deploy holds the read-only vault token, setup holds the deploy key, and no step names an operations repo or an inventory. Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/operationsPipeline.test.ts | 45 +++++++++++----- packages/lib/src/pipeline.test.ts | 60 +++++++++++++++------ 2 files changed, 76 insertions(+), 29 deletions(-) diff --git a/packages/lib/src/operationsPipeline.test.ts b/packages/lib/src/operationsPipeline.test.ts index aa695f9b..44a7ae9f 100644 --- a/packages/lib/src/operationsPipeline.test.ts +++ b/packages/lib/src/operationsPipeline.test.ts @@ -150,17 +150,28 @@ test('deploy.yml keeps its triggers and its permissions, and can be started by h /** The version the render of the next tests is at. */ const VERSION = '7.8.9'; -test('setup of the job deploy follows the checkout, runs in its root, and alone is handed the service account token', async () => { - const { workflow } = (await operations()).deploy; - const steps = workflow.jobs.deploy?.steps ?? []; - assert.match(steps[0]?.uses ?? '', /^actions\/checkout@/); - const setup = steps.find((step) => step.id === 'setup'); - assert.equal(setup?.['working-directory'], undefined); - assert.deepEqual(setup?.env, { - GITHUB_TOKEN: '${{ github.token }}', - OP_SERVICE_ACCOUNT_TOKEN: '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}', - }); - for (const step of steps) if (step !== setup) assert.equal(step.env?.OP_SERVICE_ACCOUNT_TOKEN, undefined, what(step)); +/** The repository secrets of a deploy: the key it reaches the hosts with, and the read-only token of the vault of the stacks' secrets. */ +const DEPLOY_KEY = '${{ secrets.DEPLOY_SSH_KEY }}'; +const DEPLOY_TOKEN = '${{ secrets.DEPLOY_VAULT_TOKEN }}'; +/** The verb of the job deploy: the Connect server of a slot reads another vault, so the verb's `op` never sees it. */ +const VERB = 'env -u OP_CONNECT_HOST -u OP_CONNECT_TOKEN plx deploy --environment production'; + +test('setup of the job deploy follows the checkout, runs in its root, and is handed the deploy key and, to join the overlay, the CI vault’s token; the verb alone holds the deploy token', async () => { + for (const ci_overlay of ['none', 'netbird']) { + const { workflow } = (await operations({ ci_overlay })).deploy; + const steps = workflow.jobs.deploy?.steps ?? []; + assert.match(steps[0]?.uses ?? '', /^actions\/checkout@/); + const setup = steps.find((step) => step.id === 'setup'); + assert.equal(setup?.['working-directory'], undefined); + assert.deepEqual(setup?.env, { + GITHUB_TOKEN: '${{ github.token }}', + DEPLOY_SSH_KEY: DEPLOY_KEY, + ...(ci_overlay === 'netbird' ? { OP_SERVICE_ACCOUNT_TOKEN: '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}' } : {}), + }); + for (const step of steps) + if (step !== setup) + assert.equal(step.env?.OP_SERVICE_ACCOUNT_TOKEN, step.run === VERB ? DEPLOY_TOKEN : undefined, what(step)); + } assert.equal( (await operations()).on_commit.text.includes('OP_SERVICE_ACCOUNT_TOKEN'), false, @@ -168,7 +179,7 @@ test('setup of the job deploy follows the checkout, runs in its root, and alone ); }); -test('the job deploy is the checkout, mise without an install, the install of plx and plx-ci, setup, Ansible, and the verb with the repo’s own inventory', async () => { +test('the job deploy is the checkout, mise without an install, the install of plx and plx-ci, setup, Ansible, and the verb', async () => { for (const answers of SHAPES) { const result = await renderBundled(['repo-operations'], { tenant: 'acme', ...answers }, VERSION); const deploy = (parse(textOf(result, '.github/workflows/deploy.yml')) as Workflow).jobs.deploy; @@ -182,7 +193,7 @@ test('the job deploy is the checkout, mise without an install, the install of pl `mise use -g node@24 ${tool('cli')} ${tool('cli-ci')}`, `plx-ci setup deploy --overlay ${answers.ci_overlay}`, ...ansibleSteps(VERSION), - 'plx deploy --environment production --inventory inventory', + VERB, ...leave, ], JSON.stringify(answers), @@ -191,7 +202,11 @@ test('the job deploy is the checkout, mise without an install, the install of pl for (const i of [4, 5]) assert.equal(deploy?.steps?.[i]?.['working-directory'], '${{ runner.temp }}'); assert.deepEqual([deploy?.steps?.[4]?.env, deploy?.steps?.[5]?.env], [SHIMS, COLLECTIONS]); // The input reaches the tool through the environment, where plx reads it by its value: a push has none. - assert.deepEqual(deploy?.steps?.[6]?.env, { ...COLLECTIONS, PLX_DRY_RUN: '${{ inputs.dry_run }}' }); + assert.deepEqual(deploy?.steps?.[6]?.env, { + ...COLLECTIONS, + PLX_DRY_RUN: '${{ inputs.dry_run }}', + OP_SERVICE_ACCOUNT_TOKEN: DEPLOY_TOKEN, + }); } }); @@ -269,6 +284,8 @@ test('a step of an operations repo’s workflows is one command or one pinned ac '${{ runner.temp }}', '${{ github.token }}', '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}', + DEPLOY_KEY, + DEPLOY_TOKEN, '${{ inputs.dry_run }}', "${{ always() && steps.setup.outputs.joined == 'true' }}", ]); diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 902261fb..9adac687 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -159,7 +159,13 @@ test('an app repo’s three workflows each hold the job repo in full: checkout, } }); -test('on_push deploys after the job repo, in a job of its own: checkout, mise, setup, the operations repo, Ansible, plx deploy', async () => { +/** The repository secrets of a deploy: the key it reaches the hosts with, and the read-only token of the vault of the stacks' secrets. */ +const DEPLOY_KEY = '${{ secrets.DEPLOY_SSH_KEY }}'; +const DEPLOY_TOKEN = '${{ secrets.DEPLOY_VAULT_TOKEN }}'; +/** The verb in the job deploy: the Connect server of a slot reads another vault, so the verb's `op` never sees it. */ +const VERB = 'env -u OP_CONNECT_HOST -u OP_CONNECT_TOKEN plx deploy'; + +test('on_push deploys after the job repo, in a job of its own: checkout, mise, setup, Ansible, plx deploy, and no other repo is checked out', async () => { for (const answers of SHAPES) { const deploy = (await appRepo(answers)).on_push.workflow.jobs.deploy; assert.deepEqual(needsOf(deploy), ['repo']); @@ -168,24 +174,40 @@ test('on_push deploys after the job repo, in a job of its own: checkout, mise, s 'jdx/mise-action', `mise use -g node@24 'npm:@plexus-ms/cli[allow_low_downloads=true]@${CURRENT}' 'npm:@plexus-ms/cli-ci[allow_low_downloads=true]@${CURRENT}'`, 'plx-ci setup deploy --overlay none', - 'actions/checkout', ...ansibleSteps(CURRENT), - 'plx deploy --inventory operations/inventory', + VERB, ]); // Ansible is installed outside the checkout, as plx is, and the collection where the verb's Ansible looks. - const [plx, ansible, collection, verb] = [2, 5, 6, 7].map((i) => deploy?.steps?.[i]); + const [plx, ansible, collection, verb] = [2, 4, 5, 6].map((i) => deploy?.steps?.[i]); for (const step of [plx, ansible, collection]) assert.equal(step?.['working-directory'], '${{ runner.temp }}'); - assert.deepEqual([plx?.env, ansible?.env, collection?.env, verb?.env], [SHIMS, SHIMS, COLLECTIONS, COLLECTIONS]); + assert.deepEqual( + [plx?.env, ansible?.env, collection?.env, verb?.env], + [SHIMS, SHIMS, COLLECTIONS, { ...COLLECTIONS, OP_SERVICE_ACCOUNT_TOKEN: DEPLOY_TOKEN }], + ); assert.equal(deploy?.steps?.[3]?.id, 'setup'); - // The tenant's operations repo, with the token that setup minted for it alone. - assert.deepEqual(deploy?.steps?.[4]?.with, { - repository: '${{ github.repository_owner }}/operations', - token: '${{ steps.setup.outputs.operations-token }}', - path: 'operations', - }); + // The deploy key is a repository secret handed to setup, which holds it in an agent. + assert.equal(deploy?.steps?.[3]?.env?.DEPLOY_SSH_KEY, DEPLOY_KEY); + assert.equal((deploy?.steps ?? []).filter((s) => s.uses?.startsWith('actions/checkout')).length, 1); + assert.doesNotMatch(JSON.stringify(deploy), /operations/); } }); +test('the vault of the stacks’ secrets is read with the deploy token, which only the step of plx deploy holds; setup holds the CI vault’s token only to join the overlay', async () => { + for (const ci_service_account of [true, false]) + for (const ci_overlay of ['none', 'netbird']) { + const text = (await appRepo({ ci_service_account, ci_overlay })).on_push; + const deploy = text.workflow.jobs.deploy; + const setup = deploy?.steps?.find((s) => s.id === 'setup'); + const ci = ci_service_account && ci_overlay === 'netbird' ? '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}' : undefined; + assert.equal(setup?.env?.OP_SERVICE_ACCOUNT_TOKEN, ci, JSON.stringify({ ci_service_account, ci_overlay })); + for (const step of deploy?.steps ?? []) + if (step.id !== 'setup') + assert.equal(step.env?.OP_SERVICE_ACCOUNT_TOKEN, step.run === VERB ? DEPLOY_TOKEN : undefined, what(step)); + // No job but the deploy holds either repository secret of the deploy. + assert.doesNotMatch(JSON.stringify(text.workflow.jobs.repo), /DEPLOY_/); + } +}); + test('the job repo asks for a repo slot under byom and the job deploy for a delivery slot, both for the forge’s runner under github', async () => { for (const ci_strategy of STRATEGIES) { const workflows = await appRepo({ ci_strategy }); @@ -260,11 +282,19 @@ test('setup alone is handed the service account token where the repo answers ci_ for (const job of Object.values(handed[name].workflow.jobs)) for (const step of job.steps ?? []) { const token = step.env?.OP_SERVICE_ACCOUNT_TOKEN; - if (step.id === 'setup') assert.equal(token, '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}', name); + if (step.id === 'setup' && job === handed[name].workflow.jobs.repo) + assert.equal(token, '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}', name); + else if (step.run === VERB) assert.equal(token, DEPLOY_TOKEN, name); else assert.equal(token, undefined, `${name}: ${what(step)}`); } const unhanded = await appRepo({ ci_strategy, ci_service_account: false }); - for (const name of APP) assert.doesNotMatch(unhanded[name].text, /service.account|OP_SERVICE/i, name); + // The deploy token is the verb's own, and not the CI vault's. + for (const name of APP) + assert.doesNotMatch( + unhanded[name].text.replace(/^.*DEPLOY_VAULT_TOKEN.*$/m, ''), + /service.account|OP_SERVICE/i, + name, + ); } }); @@ -418,8 +448,8 @@ test('a step of an app repo’s workflows is one command, and the only expressio '${{ github.token }}', '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}', '${{ steps.setup.outputs.server-actions-key }}', - '${{ steps.setup.outputs.operations-token }}', - '${{ github.repository_owner }}', + DEPLOY_KEY, + DEPLOY_TOKEN, '${{ github.run_attempt }}', "${{ failure() && steps.e2e.conclusion == 'failure' }}", "${{ always() && steps.setup.outputs.joined == 'true' }}", From 8d1ad881821e33eba3cf56eb8716e392611e7ee4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:40:35 +0100 Subject: [PATCH 64/91] plx deploy deploys the stacks that have the environment's file, to the host the file names, and reads no inventory The stack playbook gets the file and no inventory, user, port or environment name; a file with a problem refuses the run before any host or registry; --inventory is gone with the operations record the deploy targets read, and deployTargets.ts keeps only the map from a branch to its environment. Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/deploy.test.ts | 4 +- packages/cli/src/commands/deploy.ts | 28 ++-- packages/lib/src/deploy.ts | 202 +++++++++++------------ packages/lib/src/deployTargets.test.ts | 138 +--------------- packages/lib/src/deployTargets.ts | 176 +------------------- packages/lib/src/index.ts | 18 +- 6 files changed, 113 insertions(+), 453 deletions(-) diff --git a/packages/cli/src/commands/deploy.test.ts b/packages/cli/src/commands/deploy.test.ts index c84527cc..29c05552 100644 --- a/packages/cli/src/commands/deploy.test.ts +++ b/packages/cli/src/commands/deploy.test.ts @@ -380,7 +380,7 @@ function plxProcess(args: string[]): { status: number | null; stderr: string } { test('plx deploy has no --inventory: a deploy reads only its own repo, and the flag is an unknown option', () => { const f = fixture(); const { status, stderr } = plxProcess(['deploy', '-e', 'staging', '--inventory', join(f.root, 'inv'), '-C', f.repo]); - assert.equal(status, 2); + assert.notEqual(status, 0); assert.match(stderr, /unknown option '--inventory'/); assert.deepEqual(runs(f.fake), []); }); @@ -942,7 +942,9 @@ test('against this machine’s Docker daemon: deployed, unchanged, one service r }); // Each stack's file for staging: the host it deploys to, here this machine, and a scratch directory as the root. for (const s of ['shop', 'docs']) put(repo, { [`stacks/${run}-${s}/staging.yaml`]: 'host: localhost\n' }); + // The root of the stacks, which the platform playbook prepares on a host. const stacks = join(root, 'stacks'); + mkdirSync(stacks); // The collection of this checkout, alone where Ansible looks; community.docker is the one the ansible package brings. const collections = join(root, 'collections'); mkdirSync(join(collections, 'ansible_collections', 'plexus'), { recursive: true }); diff --git a/packages/cli/src/commands/deploy.ts b/packages/cli/src/commands/deploy.ts index a4e4f61e..85d40189 100644 --- a/packages/cli/src/commands/deploy.ts +++ b/packages/cli/src/commands/deploy.ts @@ -1,21 +1,22 @@ -// plx deploy: every stack of the checkout that has a record in an -// environment, onto the host its record names, through the stack playbook +// plx deploy: every stack of the checkout that has an environment's file, +// onto the host the file names, through the stack playbook // (§ 6 PLX-Delivery). lib's `deploy` does the work, and its header says how, // in order; this file maps the arguments and sets the exit code. // // The environment is --environment, else follows from the branch of the -// forge's run (GITHUB_EVENT_NAME, GITHUB_REF_NAME). The records are read from -// --inventory, the inventory directory of the operations repo, which is -// required in every repo, the operations repo too (`--inventory inventory`). -// The images are the commit's, --commit (a full hash, SHA-1 or SHA-256), else +// forge's run (GITHUB_EVENT_NAME, GITHUB_REF_NAME). Nothing but the checkout +// is read: the host is in each stack's file, and the secrets the file points +// at are read by the playbook, with the `op` of whoever runs the verb, in a job +// with its service account's token (OP_SERVICE_ACCOUNT_TOKEN) and by a person +// with their own session. The images are the commit's, --commit (a full hash, SHA-1 or SHA-256), else // the checkout's HEAD. Arguments after `--` go to every run of // ansible-playbook; an operand before it is refused. Exit code 1 when any // stack failed or none was deployed. An empty option value is the same as an // absent one, so a mount can always pass the flag. // -// plx deploy --environment staging --inventory ../operations/inventory -// plx deploy --inventory operations/inventory # in a job, on a push to main or develop -// plx deploy -e production --inventory inventory -- -e stack_wait_timeout=180 +// plx deploy --environment staging +// plx deploy # in a job, on a push to main or develop +// plx deploy -e production -- -e stack_wait_timeout=180 import { resolve } from 'node:path'; import { deploy, ENVIRONMENT_BRANCHES, environmentOf, UsageError } from '@plexus-ms/lib'; import type { Command } from 'commander'; @@ -23,7 +24,6 @@ import { contextOf, version } from '../program.ts'; interface Opts { environment?: string; - inventory?: string; commit?: string; dir: string; } @@ -32,23 +32,18 @@ export function register(program: Command): void { program .command('deploy') .description( - 'deploy every stack of the checkout that has a record in the environment: render its compose file with each app’s image pinned by digest, run the stack playbook against its host, all stacks at once', + 'deploy every stack of the checkout that has a file for the environment: render its compose file with each app’s image pinned by digest, run the stack playbook against its host, all stacks at once', ) .argument('[ansible-playbook-arguments...]', 'after --: arguments for every run of ansible-playbook') .option( '-e, --environment ', 'the environment deployed into (default: from the branch, in a job of the forge)', ) - .option('--inventory ', 'the operations repo’s inventory, which holds each stack’s record') .option('--commit ', 'the commit whose images are deployed (default: the checkout’s HEAD)') .option('-C, --dir ', 'the checkout to read', '.') .action(async (operands: string[], opts: Opts, command: Command) => { const ctx = contextOf(command); const ansible = afterDoubleDash(command, operands); - if (!opts.inventory) - throw new UsageError( - 'plx deploy needs the inventory its records are read from: pass --inventory /inventory, which in the operations repo itself is --inventory inventory', - ); if (opts.commit && !/^([0-9a-f]{40}|[0-9a-f]{64})$/.test(opts.commit)) throw new UsageError(`--commit ${opts.commit}: a full commit hash, 40 or 64 hex digits in lower case`); const env = process.env; @@ -59,7 +54,6 @@ export function register(program: Command): void { ); const result = await deploy(ctx, { environment, - inventory: resolve(opts.inventory), commit: opts.commit || undefined, dir: resolve(opts.dir), ansible, diff --git a/packages/lib/src/deploy.ts b/packages/lib/src/deploy.ts index 15c289ce..4db8e42f 100644 --- a/packages/lib/src/deploy.ts +++ b/packages/lib/src/deploy.ts @@ -1,9 +1,10 @@ -// deploy: brings every stack of a checkout that has a record in an -// environment onto the host the record names (§ 6 PLX-Delivery), through the -// stack playbook, plexus.platform.stack, whose header says what it does on -// the host. Every change on a host is the playbook's: this verb finds, -// renders, resolves, runs ansible-playbook and reports, and holds no rollback -// and no health logic of its own. In order: +// deploy: brings every stack of a checkout that has an environment's file onto +// the host the file names (§ 6 PLX-Delivery), through the stack playbook, +// plexus.platform.stack, whose header says what it does on the host. Every +// change on a host is the playbook's: this verb finds, renders, resolves, runs +// ansible-playbook and reports, and holds no rollback and no health logic of +// its own. It reads the checkout and nothing else of the repo's tenant: no +// second repo, no inventory. In order: // // 1. The stacks, from the checkout (`loadStacks`, stacks.ts). A checkout // with a problem the loader reports is refused with the loader's words, @@ -12,11 +13,12 @@ // stack is refused, for a deploy that deploys nothing is no success, // and the refusal names every compose file inside an app, where stacks // lived before. -// 2. The records, from the inventory given (deployTargets.ts): a stack's -// record is the one whose `name` is the stack's and whose `environment` -// is the one deployed, and its file's plexus_deploy_target, -// ssh://@
[:], is where the stack goes. Where no -// stack has a record, the run ends here: the summary names each stack, +// 2. The environment's files: a stack's file is `.yaml` in its +// directory (environments.ts), and its `host` is where the stack goes. A +// file with a problem refuses the run, with every problem of every +// stack's file for this environment, before any host or registry is +// reached; the files of other environments are not read for it. Where no +// stack has the file, the run ends here: the summary names each stack, // and the verb fails, for nothing was deployed; it needs no Ansible. // 3. The rendering: each compose.yaml with ${PLEXUS_TAG}, bare or with an // error message, set to the commit (given, else the checkout's HEAD), @@ -47,18 +49,20 @@ // looks), refuses the run, naming what to install; a check that takes // more than two minutes is stopped and refuses the run, saying so. Which // version of the collection is installed is not checked. -// 5. The runs, one per stack with a record, all at once: -// ansible-playbook -i
, [-u ] [-e ansible_port=] -// --ssh-common-args '-o StrictHostKeyChecking=accept-new' -// -e stack_name= -e stack_environment= +// 5. The runs, one per stack with the file, all at once: +// ansible-playbook --ssh-common-args '-o StrictHostKeyChecking=accept-new' +// -e stack_name= -e stack_environment_file= // -e stack_compose_file= [--check --diff] // [] plexus.platform.stack -// in the run's directory, so that no ansible.cfg of the checkout is read, -// with stdin from /dev/null and the default callback printing its results -// as JSON. A run's output, both streams in one, is held until it ends and -// then written as one block under `── - → ──`, -// so no two runs' lines meet. A run that takes more than an hour is -// stopped and fails. +// with no inventory, user or port: the playbook takes the host from the +// file, and the environment's name from its name; it resolves the file's +// `op://` pointers where it runs, with the `op` there (§ 1 PLX-Secrets). +// The run is in the run's directory, so that no ansible.cfg of the +// checkout is read, with stdin from /dev/null and the default callback +// printing its results as JSON. A run's output, both streams in one, is +// held until it ends and then written as one block under +// `── - → ──`, so no two runs' lines meet. A +// run that takes more than an hour is stopped and fails. // 6. The summary, one line per stack of the checkout, by name: // ✓ -: deployed | unchanged | would deploy // ✗ -: rolled back: | failed: @@ -67,18 +71,19 @@ // `. The exit code decides over the text: a run whose // last line is a success and whose exit is not 0 is `✗ …: failed: // ansible-playbook exited , though its last line says `. A -// stack whose record sits in a file without a -// plexus_deploy_target is `✗ …: its record in names no -// plexus_deploy_target`, and one without a record `- …: no record in -// ; not deployed`. A stack's failure stops no other's run; +// stack without the environment's file is `- …: no .yaml; +// not deployed`. A stack's failure stops no other's run; // the verb fails when any line is ✗. The directory of the run is removed. // // What a run needs where it runs: Docker with buildx, logged in to every // registry an app's image is in (for the digests); ansible-playbook on the // PATH and the collection plexus.platform where Ansible looks, which brings // community.docker at the version its galaxy.yml names (for any stack with a -// record); and SSH access as the user of each target, whose host key is taken -// on first contact (accept-new) into the known_hosts of whoever runs it. +// file); SSH access to each file's host as the user it names, whose host key +// is taken on first contact (accept-new) into the known_hosts of whoever runs +// it; and, where an environment has secrets, `op` on the PATH, signed in or +// with OP_SERVICE_ACCOUNT_TOKEN, which the playbook reads them with. A person +// runs the same verb from a checkout with their own session of the vault. // // Every process the verb starts runs in a process group of its own, with a // limit: two minutes for a read (a digest, the syntax check), an hour for a @@ -96,27 +101,19 @@ // run is kept and named, so that each command printed runs as it stands; // without `--check --diff` it is the deploy. // -// plx deploy --environment staging --inventory ../operations/inventory -// plx deploy --inventory operations/inventory # in a job, the environment from the branch -// plx -n deploy -e production --inventory inventory # the playbook's --check --diff -// plx deploy -e staging --inventory inv -- -e stack_wait_timeout=180 +// plx deploy --environment staging +// plx deploy # in a job, the environment from the branch +// plx -n deploy -e production # the playbook's --check --diff +// plx deploy -e staging -- -e stack_wait_timeout=180 import { rmSync } from 'node:fs'; import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { join, relative } from 'node:path'; import { type Document, isAlias, isMap, isScalar, isSeq, parseDocument, visit } from 'yaml'; import { COMMIT_SHA_PLACEHOLDER, parseCompose } from './compose.ts'; import type { Context } from './context.ts'; -import { - type DeployLeg, - deployLegs, - readInventory, - recordsWithoutTarget, - selectDeployTargets, - targetsIn, - type Untargeted, -} from './deployTargets.ts'; import { write } from './effects.ts'; +import type { Environment } from './environments.ts'; import { detailOf, ExecError, onInterrupt, render, TimeoutError } from './io.ts'; import { APPS_DIR } from './model.ts'; import { isFile, loadStacks, type Stack, type StackProblem } from './stacks.ts'; @@ -124,8 +121,6 @@ import { UsageError } from './version.ts'; export interface DeployOptions { environment: string; - /** The operations repo's inventory directory, which the records are read from. */ - inventory: string; /** The commit whose images are deployed; default the checkout's HEAD, read only where a stack needs it. */ commit?: string; /** The checkout; default the cwd. */ @@ -144,14 +139,13 @@ export type DeployOutcome = | 'rolled back' | 'failed' | 'interrupted' - | 'no target' - | 'no record'; + | 'no file'; export interface StackOutcome { stack: string; environment: string; - /** The record's plexus_deploy_target, where it has one. */ - target?: string; + /** The `host` of the stack's file for the environment, as written. */ + host?: string; outcome: DeployOutcome; ok: boolean; /** The summary line without its mark: `-: …`. */ @@ -202,24 +196,30 @@ const ANSIBLE_ENV = { ANSIBLE_NOCOLOR: '1', }; +/** One stack's deploy: its name, the environment's file and the `host` that names. */ +interface Leg { + stack: string; + file: string; + host: string; +} + export async function deploy(ctx: Context, options: DeployOptions): Promise { const { environment } = options; const dir = options.dir ?? '.'; const repo = await loadStacks(ctx, dir); refuseProblems(repo.problems); if (repo.stacks.length === 0) throw new Error(await noStack(ctx, repo.root)); - const files = await readInventory(ctx, options.inventory); - const names = repo.stacks.map((s) => s.name); - const { legs, untargeted } = deployLegs( - targetsIn(selectDeployTargets(files), environment), - names, - recordsWithoutTarget(files, environment), + const named = repo.stacks.map((s) => ({ stack: s, file: s.environments.find((e) => e.name === environment) })); + refuseFiles(repo.root, named, environment); + const legs = named.flatMap(({ stack, file }): Leg[] => + file ? [{ stack: stack.name, file: file.file, host: file.host as string }] : [], ); - const everyStack = (outcomes: StackOutcome[]) => withTheRest(outcomes, untargeted, names, environment); + const names = repo.stacks.map((s) => s.name); + const everyStack = (outcomes: StackOutcome[]) => withTheRest(outcomes, names, environment); if (legs.length === 0) { const outcomes = everyStack([]); report(ctx, outcomes); - if (untargeted.length === 0) ctx.done(`no stack has a record in ${environment}: nothing was deployed`, false); + ctx.done(`no stack has a ${environment}.yaml: nothing was deployed`, false); return { environment, stacks: outcomes, ok: false }; } @@ -232,7 +232,7 @@ export async function deploy(ctx: Context, options: DeployOptions): Promise repo.stacks.find((s) => s.name === name) as Stack; - const rendered = await Promise.all(legs.map(async (leg) => renderStack(ctx, stackOf(leg.app), commitOf))); + const rendered = await Promise.all(legs.map(async (leg) => renderStack(ctx, stackOf(leg.stack), commitOf))); const unresolved = rendered.flatMap((r) => ('unresolved' in r ? r.unresolved : [])); if (unresolved.length > 0) throw new Error(`${unresolved.join('\n')}\nno stack was deployed`); @@ -245,7 +245,7 @@ export async function deploy(ctx: Context, options: DeployOptions): Promise { - const running = legs.filter((leg) => !ran.some((o) => o.stack === leg.app)); + const running = legs.filter((leg) => !ran.some((o) => o.stack === leg.stack)); if (ctx.dryRun) kept(); else rmSync(scratch, { recursive: true, force: true }); report(ctx, everyStack([...ran, ...running.map((leg) => interrupted(leg, environment, started))])); @@ -270,24 +270,19 @@ export async function deploy(ctx: Context, options: DeployOptions): Promise noTarget(u, environment))]; +function withTheRest(ran: StackOutcome[], names: string[], environment: string): StackOutcome[] { + const outcomes = [...ran]; for (const name of names) if (!outcomes.some((o) => o.stack === name)) outcomes.push({ stack: name, environment, - outcome: 'no record', + outcome: 'no file', ok: true, - line: `${name}-${environment}: no record in ${environment}; not deployed`, + line: `${name}-${environment}: no ${environment}.yaml; not deployed`, }); return outcomes.sort((a, b) => a.stack.localeCompare(b.stack)); } @@ -295,29 +290,20 @@ function withTheRest( /** The summary: one line per stack. */ function report(ctx: Context, outcomes: StackOutcome[]): void { for (const o of outcomes) - if (o.outcome === 'no record') ctx.say(`- ${o.line}`); + if (o.outcome === 'no file') ctx.say(`- ${o.line}`); else ctx.done(o.line, o.ok); } /** A stack whose run was under way, or had not begun, when a signal ended plx. */ -const interrupted = (leg: DeployLeg, environment: string, started: boolean): StackOutcome => ({ - stack: leg.app, +const interrupted = (leg: Leg, environment: string, started: boolean): StackOutcome => ({ + stack: leg.stack, environment, - target: leg.host, + host: leg.host, outcome: 'interrupted', ok: false, line: started - ? `${leg.app}-${environment}: interrupted: plx was stopped while the playbook ran, which may have left the host mid-deploy` - : `${leg.app}-${environment}: interrupted: plx was stopped before the playbook ran; no host was reached`, -}); - -/** A stack whose record names no target: a failure that names the file. */ -const noTarget = ({ app: stack, files }: Untargeted, environment: string): StackOutcome => ({ - stack, - environment, - outcome: 'no target', - ok: false, - line: `${stack}-${environment}: its record in ${files.join(' and ')} names no plexus_deploy_target`, + ? `${leg.stack}-${environment}: interrupted: plx was stopped while the playbook ran, which may have left the host mid-deploy` + : `${leg.stack}-${environment}: interrupted: plx was stopped before the playbook ran; no host was reached`, }); /** @@ -337,6 +323,23 @@ async function noStack(ctx: Context, root: string): Promise { return lines.join('\n'); } +/** + * The problems of every stack's file for the environment, each under the + * file's path in the repo, as one refusal; the files of other environments + * are not asked. + */ +function refuseFiles( + root: string, + named: { stack: Stack; file: Environment | undefined }[], + environment: string, +): void { + const lines = named.flatMap(({ stack, file }) => + (file?.problems ?? []).map((problem) => join(relative(root, stack.dir), problem)), + ); + if (lines.length > 0) + throw new UsageError(`${lines.join('\n')}\nno stack was deployed into ${environment}; plx doctor reports the same`); +} + /** The loader's problems, but an app no stack uses, as one refusal. */ function refuseProblems(problems: StackProblem[]): void { const blocking = problems.filter((p) => p.code !== 'unused-app'); @@ -493,59 +496,40 @@ async function checkAnsible(ctx: Context, scratch: string, version = '@
[:], as ansible-playbook's arguments. */ -function hostArguments(target: string): string[] { - const match = /^(?:ssh:\/\/)?(?:([^@/]+)@)?(\[[^\]]+\]|[^:/@]+)(?::(\d+))?\/?$/.exec(target); - if (!match) throw new UsageError(`plexus_deploy_target ${target}: not of the form ssh://@
[:]`); - const [, user, address = '', port] = match; - return [ - '-i', - `${address.replace(/^\[(.*)\]$/, '$1')},`, - ...(user ? ['-u', user] : []), - ...(port ? ['-e', `ansible_port=${port}`] : []), - ]; -} - /** One stack's run of the playbook: its block of output, written when it ends, and what it came to. */ async function runStack( ctx: Context, options: DeployOptions, - leg: DeployLeg, + leg: Leg, rendered: string, scratch: string, ): Promise { const { environment } = options; - const stack = leg.app; + const { stack } = leg; const project = `${stack}-${environment}`; const failed = (why: string): StackOutcome => ({ stack, environment, - target: leg.host, + host: leg.host, outcome: 'failed', ok: false, line: `${project}: failed: ${why}`, }); - let args: string[]; - try { - args = hostArguments(leg.host); - } catch (error) { - return failed((error as Error).message); - } const file = join(scratch, `${project}.compose.yaml`); await ctx.stage(write(file, rendered)); - args.push( + const args = [ '--ssh-common-args', '-o StrictHostKeyChecking=accept-new', '-e', `stack_name=${stack}`, '-e', - `stack_environment=${environment}`, + `stack_environment_file=${leg.file}`, '-e', `stack_compose_file=${file}`, ...(ctx.dryRun ? ['--check', '--diff'] : []), ...(options.ansible ?? []), PLAYBOOK, - ); + ]; let output: string; let code = 0; try { @@ -580,7 +564,7 @@ async function runStack( ?.trim(); return failed(`ansible-playbook exited ${code}${why ? `: ${why}` : ''}`); } - return { stack, environment, target: leg.host, outcome: known[1], ok: known[2], line: `${project}: ${result}` }; + return { stack, environment, host: leg.host, outcome: known[1], ok: known[2], line: `${project}: ${result}` }; } /** A full commit hash, SHA-1 or SHA-256, in lower case. */ diff --git a/packages/lib/src/deployTargets.test.ts b/packages/lib/src/deployTargets.test.ts index 39179494..0aeb671d 100644 --- a/packages/lib/src/deployTargets.test.ts +++ b/packages/lib/src/deployTargets.test.ts @@ -1,142 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { Context } from './context.ts'; -import { - deployLegs, - ENVIRONMENT_BRANCHES, - environmentOf, - parseInventoryFile, - readInventory, - recordsWithoutTarget, - selectDeployTargets, - targetsIn, -} from './deployTargets.ts'; -import { fakeIo } from './testing/fakeIo.ts'; - -const hostA = `--- -plexus_deploy_target: "ssh://deploy@host-a.example:22" -plexus_apps: - - name: beszel - source: plexus-ms-tenant/platform - port: 3011 - - name: 'pocket-id' - port: 3012 -other_key: x -`; - -test('parseInventoryFile reads the target, the app names and their environments, production by default', () => { - assert.deepEqual(parseInventoryFile('inventory/host_vars/host-a.yml', hostA), { - path: 'inventory/host_vars/host-a.yml', - target: 'ssh://deploy@host-a.example:22', - apps: [ - { app: 'beszel', environment: 'production' }, - { app: 'pocket-id', environment: 'production' }, - ], - }); - assert.deepEqual( - parseInventoryFile( - 's.yml', - 'plexus_deploy_target: ssh://s\nplexus_apps:\n - name: website\n environment: staging\n', - ).apps, - [{ app: 'website', environment: 'staging' }], - ); - assert.deepEqual(parseInventoryFile('g.yml', 'ansible_user: root\n'), { path: 'g.yml', target: undefined, apps: [] }); - assert.deepEqual(parseInventoryFile('e.yml', ''), { path: 'e.yml', target: undefined, apps: [] }); -}); - -const prod = (app: string) => ({ app, environment: 'production' }); - -test('selectDeployTargets maps the deployments of files with a target, sorted, and skips files without one', () => { - const map = selectDeployTargets([ - { path: 'inventory/host_vars/host-b.yml', target: 'ssh://deploy@host-b', apps: [prod('website')] }, - { path: 'inventory/group_vars/all.yml', apps: [prod('beszel')] }, - { - path: 'inventory/host_vars/host-a.yml', - target: 'ssh://deploy@host-a', - apps: [prod('beszel'), prod('pocket-id')], - }, - ]); - assert.deepEqual(Object.entries(map), [ - ['beszel', { production: 'ssh://deploy@host-a' }], - ['pocket-id', { production: 'ssh://deploy@host-a' }], - ['website', { production: 'ssh://deploy@host-b' }], - ]); -}); - -test('one app, two environments: two records, on one VM or on two, and targetsIn picks one environment', () => { - const map = selectDeployTargets([ - { - path: 'inventory/host_vars/host-a.yml', - target: 'ssh://deploy@host-a', - apps: [prod('website'), { app: 'website', environment: 'staging' }], - }, - { - path: 'inventory/host_vars/host-b.yml', - target: 'ssh://deploy@host-b', - apps: [{ app: 'my-app', environment: 'staging' }], - }, - { path: 'inventory/host_vars/host-c.yml', target: 'ssh://deploy@host-c', apps: [prod('my-app')] }, - ]); - assert.deepEqual(map, { - 'my-app': { production: 'ssh://deploy@host-c', staging: 'ssh://deploy@host-b' }, - website: { production: 'ssh://deploy@host-a', staging: 'ssh://deploy@host-a' }, - }); - assert.deepEqual(targetsIn(map, 'staging'), { 'my-app': 'ssh://deploy@host-b', website: 'ssh://deploy@host-a' }); - assert.deepEqual(targetsIn(map, 'preview'), {}); -}); - -test('an app declared with a target in two files for the same environment is an error that names both', () => { - assert.throws( - () => - selectDeployTargets([ - { path: 'inventory/host_vars/host-a.yml', target: 'a', apps: [prod('beszel')] }, - { path: 'inventory/group_vars/apphosts.yml', target: 'b', apps: [prod('beszel')] }, - ]), - /"beszel" in production.*inventory\/group_vars\/apphosts\.yml and inventory\/host_vars\/host-a\.yml/, - ); -}); - -test('deployLegs: a leg per app of the repo with a target, sorted; the rest are named, and foreign records start nothing', () => { - const targets = { beszel: 'ssh://plexus@host-c', website: 'ssh://plexus@host-a' }; - assert.deepEqual(deployLegs(targets, ['pocket-id', 'beszel']), { - legs: [{ app: 'beszel', host: 'ssh://plexus@host-c' }], - untargeted: [], - without: ['pocket-id'], - }); - assert.deepEqual(deployLegs(targets, []), { legs: [], untargeted: [], without: [] }); -}); - -test('recordsWithoutTarget: the records of an environment in files without a target, unless another file gives one', () => { - const files = [ - { path: 'inventory/host_vars/vm103.yml', apps: [prod('pocket-id'), { app: 'website', environment: 'staging' }] }, - { path: 'inventory/group_vars/all.yml', apps: [prod('pocket-id'), prod('beszel')] }, - { path: 'inventory/host_vars/host-a.yml', target: 'ssh://deploy@host-a', apps: [prod('beszel')] }, - ]; - assert.deepEqual(recordsWithoutTarget(files, 'production'), { - 'pocket-id': ['inventory/group_vars/all.yml', 'inventory/host_vars/vm103.yml'], - }); - assert.deepEqual(recordsWithoutTarget(files, 'staging'), { website: ['inventory/host_vars/vm103.yml'] }); -}); - -test('an app of the repo with a record and no target is neither a leg nor without, with its file', async () => { - const io = fakeIo({ - inv: { - host_vars: { - 'vm103.yml': 'plexus_apps:\n - name: pocket-id\n port: 3012\n', - 'vm104.yml': 'plexus_deploy_target: ssh://plexus@vm104\nplexus_apps: [{name: beszel}]\n', - }, - }, - }); - const files = await readInventory(new Context({}, io), '/inv'); - const { legs, untargeted, without } = deployLegs( - targetsIn(selectDeployTargets(files), 'production'), - ['pocket-id', 'beszel', 'unrecorded'], - recordsWithoutTarget(files, 'production'), - ); - assert.deepEqual(legs, [{ app: 'beszel', host: 'ssh://plexus@vm104' }]); - assert.deepEqual(without, ['unrecorded']); - assert.deepEqual(untargeted, [{ app: 'pocket-id', files: ['/inv/host_vars/vm103.yml'] }]); -}); +import { ENVIRONMENT_BRANCHES, environmentOf } from './deployTargets.ts'; test('the environment follows the branch on a push or a run by hand, and a given one stands in', () => { assert.equal(environmentOf('push', 'main'), 'production'); diff --git a/packages/lib/src/deployTargets.ts b/packages/lib/src/deployTargets.ts index fb6fc491..f41d7a9b 100644 --- a/packages/lib/src/deployTargets.ts +++ b/packages/lib/src/deployTargets.ts @@ -1,32 +1,8 @@ -// deploy targets: where the deploy verb reaches each stack an operations -// repo's records name (§ 3 PLX-Platform), read from the repo's inventory. -// -// An inventory file, host_vars for a VM or group_vars for a group, carries -// `plexus_deploy_target` (ssh://@
[:]) and the -// `plexus_apps` records it hosts, each with a `name` and an optional -// `environment` (`production` when absent). `selectDeployTargets` maps every -// deployment, an app in an environment, of a file that names a target to that -// target. A deployment whose file carries no target is left out of the map, -// so the app has no target in that environment, and `plx deploy` deploys -// nothing for it. `deployLegs` takes the names a repo deploys, its stacks' -// (a record's `name` is a stack's), and is stricter: a stack whose record in -// the environment sits in a file without a target is a failure that names -// the stack and the file, since the repo means to deploy it and nothing -// would; a stack with no record in the environment at all gets no leg. The -// same name may have one record per environment, on the same VM or on two; -// the same name in the same environment declared in two files that both name -// a target has no one place to deploy to, and that is an error, never a pick. -// -// `environmentOf` is the one place that says which environment a branch deploys -// into, for `plx` and `plx-ci`. -import { join } from 'node:path'; -import { parse } from 'yaml'; -import type { Context } from './context.ts'; -import { UsageError } from './version.ts'; +// the environment a branch deploys into (§ 3 PLX-Delivery): `environmentOf` +// is the one place that says it, for `plx` and `plx-ci`. Where a stack goes is +// not here: it is the `host` of the stack's environment file (environments.ts). -const VARS_DIRS = ['group_vars', 'host_vars']; - -/** The environment a record without one is in. */ +/** The environment main deploys into. */ export const DEFAULT_ENVIRONMENT = 'production'; /** @@ -45,147 +21,3 @@ export function environmentOf(event: string, ref: string, given = ''): string { /** The branches that deploy, each into its environment: the rule `environmentOf` applies, and the list a refusal names. */ export const ENVIRONMENT_BRANCHES: Readonly> = { main: DEFAULT_ENVIRONMENT, develop: 'staging' }; - -/** App name → environment → deploy target. */ -export type DeployTargets = Record>; - -/** App name → deploy target, for one environment. */ -export type EnvironmentTargets = Record; - -export interface Deployment { - app: string; - environment: string; -} - -export interface InventoryFile { - /** The file's path, for the error that names it. */ - path: string; - target?: string; - apps: Deployment[]; -} - -/** The keys the verb reads from an inventory file's text; anything else is ignored. */ -export function parseInventoryFile(path: string, text: string): InventoryFile { - const data: unknown = parse(text); - const vars = data !== null && typeof data === 'object' ? (data as Record) : {}; - const target = typeof vars.plexus_deploy_target === 'string' ? vars.plexus_deploy_target : undefined; - const records = Array.isArray(vars.plexus_apps) ? vars.plexus_apps : []; - const apps = records.flatMap((r): Deployment[] => { - if (r === null || typeof r !== 'object') return []; - const { name, environment } = r as { name?: unknown; environment?: unknown }; - if (typeof name !== 'string') return []; - return [{ app: name, environment: typeof environment === 'string' ? environment : DEFAULT_ENVIRONMENT }]; - }); - return { path, target, apps }; -} - -/** The map from the files read: deterministic, and loud about a deployment with two targets. */ -export function selectDeployTargets(files: InventoryFile[]): DeployTargets { - const targets: DeployTargets = {}; - const declaredIn: Record = {}; - for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) { - if (file.target === undefined) continue; - for (const { app, environment } of file.apps) { - const key = `${app}@${environment}`; - if (key in declaredIn) - throw new Error( - `app "${app}" in ${environment} is declared with a deploy target in both ${declaredIn[key]} and ${file.path}`, - ); - const envs = targets[app] ?? {}; - envs[environment] = file.target; - targets[app] = envs; - declaredIn[key] = file.path; - } - } - return Object.fromEntries( - Object.entries(targets) - .sort(([a], [b]) => a.localeCompare(b)) - .map(([app, envs]) => [app, Object.fromEntries(Object.entries(envs).sort(([a], [b]) => a.localeCompare(b)))]), - ); -} - -/** The flat map of one environment: the apps that have a deployment there, and their targets. */ -export function targetsIn(targets: DeployTargets, environment: string): EnvironmentTargets { - const flat: EnvironmentTargets = {}; - for (const [app, envs] of Object.entries(targets)) { - const target = envs[environment]; - if (target !== undefined) flat[app] = target; - } - return flat; -} - -/** One deploy: an app and where it deploys. */ -export interface DeployLeg { - app: string; - host: string; -} - -/** - * App → the files that hold its record in the environment and name no - * target, for the apps that have no target there from any other file. - */ -export function recordsWithoutTarget(files: InventoryFile[], environment: string): Record { - const targeted = targetsIn(selectDeployTargets(files), environment); - const found: Record = {}; - for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) { - if (file.target !== undefined) continue; - for (const d of file.apps) { - if (d.environment !== environment || d.app in targeted) continue; - const paths = found[d.app] ?? []; - if (!paths.includes(file.path)) paths.push(file.path); - found[d.app] = paths; - } - } - return found; -} - -/** An app a repo holds whose record in the environment names no target, and the files that hold the record. */ -export interface Untargeted { - app: string; - files: string[]; -} - -/** - * The deploys of the apps a repo holds itself, in one environment: a leg per - * app with a target there; `untargeted`, the apps with a record there whose - * file names no target, which the caller refuses; and `without`, the apps - * with no record there at all, which have no deployment in it. So the - * inventory's records of apps built elsewhere start nothing here. - */ -export function deployLegs( - targets: EnvironmentTargets, - apps: string[], - recordsWithout: Record = {}, -): { legs: DeployLeg[]; untargeted: Untargeted[]; without: string[] } { - const legs: DeployLeg[] = []; - const untargeted: Untargeted[] = []; - const without: string[] = []; - for (const app of [...apps].sort()) { - const host = targets[app]; - const files = recordsWithout[app]; - if (host !== undefined) legs.push({ app, host }); - else if (files !== undefined) untargeted.push({ app, files }); - else without.push(app); - } - return { legs, untargeted, without }; -} - -/** Read every group_vars and host_vars file under the inventory directory. */ -export async function readInventory(ctx: Context, inventory: string): Promise { - const files: InventoryFile[] = []; - let found = false; - for (const sub of VARS_DIRS) { - const dir = join(inventory, sub); - const entries = await ctx.readDir(dir).catch(() => undefined); - if (entries === undefined) continue; - found = true; - for (const e of entries) { - if (e.directory || !/\.ya?ml$/.test(e.name)) continue; - const path = join(dir, e.name); - files.push(parseInventoryFile(path, await ctx.readFile(path))); - } - } - if (!found && (await ctx.readDir(inventory).catch(() => undefined)) === undefined) - throw new UsageError(`no inventory directory at ${inventory}`); - return files; -} diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index b93c9ec9..de6c3f29 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -42,23 +42,7 @@ export { renderCommitSha, type StackOutcome, } from './deploy.ts'; -export { - DEFAULT_ENVIRONMENT, - type DeployLeg, - type Deployment, - type DeployTargets, - deployLegs, - ENVIRONMENT_BRANCHES, - type EnvironmentTargets, - environmentOf, - type InventoryFile, - parseInventoryFile, - readInventory, - recordsWithoutTarget, - selectDeployTargets, - targetsIn, - type Untargeted, -} from './deployTargets.ts'; +export { DEFAULT_ENVIRONMENT, ENVIRONMENT_BRANCHES, environmentOf } from './deployTargets.ts'; export { type AppFacts, CHECKS, From 73971c5f5e02d33bf147b6fc2dec16b23ce5d043 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:41:49 +0100 Subject: [PATCH 65/91] plx-ci setup deploy holds the deploy key from a repository secret, reads nothing from the vault and mints no token for a second repo It puts op where the stack playbook finds it, reads the vault only to join the overlay, and no longer knows an operations repo: --operations-repo, operations-token and isOperationsRepo are gone. Co-Authored-By: Claude Sonnet 5.5 --- packages/cli-ci/src/commands/setup.ts | 63 +++++++++++++-------------- packages/cli-ci/src/core/setup.ts | 62 +++++++++++++------------- packages/cli-ci/src/core/vault.ts | 4 +- packages/lib/src/index.ts | 1 - packages/lib/src/model.ts | 15 ------- 5 files changed, 63 insertions(+), 82 deletions(-) diff --git a/packages/cli-ci/src/commands/setup.ts b/packages/cli-ci/src/commands/setup.ts index ccc6801b..2025ba9e 100644 --- a/packages/cli-ci/src/commands/setup.ts +++ b/packages/cli-ci/src/commands/setup.ts @@ -10,12 +10,13 @@ // repo; `npm` or `github`, a package repo's packages, to npm or // to the forge's package registry; `nothing`, as an operations // repo's. -// deploy plx deploy, of an app repo or of the operations repo. The -// checkout the step runs in (the cwd) is the operations repo -// where its root marker lists the operations template, by the -// rule plx has for it (isOperationsRepo of @plexus-ms/lib); no -// marker, or one that cannot be read, is an app repo. In the -// operations repo the step therefore follows the checkout. +// deploy plx deploy, of any repo that has stacks: the same for every +// repo, since a deploy reads only its own checkout. The step +// holds the deploy key, a repository secret, in an SSH agent, and +// puts the vault's CLI where the stack playbook finds it; the +// playbook resolves the stacks' secrets with the read-only token +// of the vault of the tenant, another repository secret, which +// the workflow hands the step of `plx deploy` alone. // changeset the job that commits the changeset a bump of the update bot // owes, and pushes it to the bot's branch. // update the job that takes a version (plx update): pushes a branch @@ -42,17 +43,21 @@ // and the runner no `op`, as the forge's own runners have none, install // the pinned version into RUNNER_TEMP/op, verified by its signature // (core/op.ts says how, and where the version is stated); a runner that -// has `op` is left as it is. A job with nothing to read installs nothing. +// has `op` is left as it is. A job with nothing to read installs nothing, +// but a deploy job, whose playbook reads the stacks' secrets with `op` +// under a token of its own, installs it all the same, and its directory +// is put on the PATH of the later steps (step 10). // Where the job has no credential, as the job of a pull request from a // fork has none, a repo job reads nothing from the vault, says so in one // line, a warning annotation of the run, and goes on at step 7 with the // logins, which are its own token's: no server-actions key and no overlay // join, so that the verbs run without the remote cache, except where the // runner itself names cache servers and tokens, as a slot of a runner -// host does. A deploy job, a repo job publishing images in the workflow -// on_push, whose images carry the repo's one key, and a changeset or -// update job without the App on the forge fail there, in one line that -// names the credentials missing; the last names both ways to the App. +// host does. A repo job publishing images in the workflow on_push, whose +// images carry the repo's one key, a deploy job that joins the overlay, +// and a changeset or update job without the App on the forge fail there, +// in one line that names the credentials missing; the last names both +// ways to the App. // 4. Read from the vault `-ci` what the job needs, every read through // the one function of core/vault.ts, which reaches the vault through the // runner's Connect server where the runner carries one and with the @@ -65,15 +70,16 @@ // turbo-cache/shared-token and turbo-cache/trusted-token. // Publishing no image, only the latter three, and where // there is no overlay to join nothing at all. -// deploy deploy-ssh/private key (as OpenSSH); except in the -// operations repo itself, github-app/client-id, which is -// no secret and is not masked, and github-app/private-key; -// on a forge runner with `--overlay netbird`, also -// netbird/setup-key +// deploy on a forge runner with `--overlay netbird`, netbird/setup-key +// and nothing else: the deploy key is no item of the vault +// but the repository secret DEPLOY_SSH_KEY, which a job +// without it fails for in one line, as nothing can be +// deployed // changeset without the App on the forge: github-app/client-id and // update github-app/private-key -// A key pasted into a one-line field gets its lines back, and each of -// them is masked as it is restored. +// A key pasted into a one-line field, of the vault or of the repository +// secret, gets its lines back, and each of them is masked as it is +// restored. // 5. update: where the runner has no `gh`, which plx update asks the forge // with, install the pinned version with mise (core/gh.ts), before any // token is minted; a runner without mise either fails in one line. @@ -82,9 +88,7 @@ // never leaves this process: the calls to the forge's API are handed the // JWT on stdin and run without the App's key and the vault's // credentials. -// deploy the operations repo (`--operations-repo`, default -// `operations`), contents read; none in the operations -// repo itself, whose checkout holds the inventory +// deploy none: a deploy reads only its own repo // changeset the job's own repo, contents write // update the job's own repo, contents, pull requests and workflows // write @@ -105,7 +109,7 @@ // owner's scope, in lower case, to that registry, so that // `changeset publish` asks it which versions exist // deploy: start an SSH agent on a socket under RUNNER_TEMP and add the -// deploy key. +// deploy key, DEPLOY_SSH_KEY. // 8. On a forge runner, where step 4 read a setup key: join the overlay as // an ephemeral peer named `ci--`, and wait until the cache // host resolves (repo) or the network map names a peer (deploy, whose @@ -126,8 +130,6 @@ // 10. Hand later steps what they need. As outputs of the step: // repo server-actions-key, publishing images, for the build and // publish steps alone -// deploy operations-token, for the checkout of the operations repo, -// except in the operations repo itself // changeset app-token, for the checkout that pushes and, in update, // update for gh (GH_TOKEN) // repo and joined=true, where the job joined the overlay @@ -137,14 +139,15 @@ // PLX_TURBO_TRUSTED_TOKEN where step 4 read them; PLX_TURBO_TRUSTED=local // (step 9); SSH_AUTH_SOCK. No secret of the vault is a variable of the job // but the two cache tokens. First on the job's PATH (GITHUB_PATH): the -// directory of the gh installed in step 5. +// directory of the gh installed in step 5, and of the op installed in +// step 3 for a deploy job. // // Under --dry-run it reads and masks, calls no API, and writes, installs and // starts nothing. Exit code 1 where the refusal, a missing credential, // a read, the token, the install of op or gh, or a deploy job's join fails; // 2 for a mistake in the arguments, among them an option of another kind of // job, before anything is read: `--private-packages` belongs to repo, -// changeset and update, `--publishes` to repo, `--operations-repo` to deploy. +// changeset and update, `--publishes` to repo. // // plx-ci setup repo --overlay netbird --private-packages // plx-ci setup repo --publishes github @@ -185,15 +188,10 @@ export function register(program: Command): void { .choices(PUBLISHES) .default('images'), ) - .option( - '--operations-repo ', - 'deploy: the tenant’s operations repo, in the owner’s organisation, which an app repo’s deploy reads', - 'operations', - ) .action( async ( job: Job, - opts: { overlay: Overlay; privatePackages?: boolean; publishes: Publishes; operationsRepo: string }, + opts: { overlay: Overlay; privatePackages?: boolean; publishes: Publishes }, command: Command, ) => { for (const [option, key, kinds] of OWN) { @@ -211,5 +209,4 @@ export function register(program: Command): void { const OWN: [string, string, Job[]][] = [ ['--private-packages', 'privatePackages', ['repo', 'changeset', 'update']], ['--publishes', 'publishes', ['repo']], - ['--operations-repo', 'operationsRepo', ['deploy']], ]; diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts index f437d1c8..06cbf6ec 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -7,7 +7,6 @@ import { detailOf, ENVIRONMENT_BRANCHES, environmentOf, - isOperationsRepo, orAbsent, type Plan, run, @@ -55,8 +54,6 @@ export interface SetupOptions { privatePackages?: boolean; /** What the repo's publish puts into a registry; a repo job's, `images` unless named. */ publishes?: Publishes; - /** The tenant's operations repo, in the owner's organisation, whose inventory an app repo's deploy reads. */ - operationsRepo?: string; } /** The forge's registries, which the job's own token logs in to. */ @@ -99,11 +96,11 @@ function refuseOnPushWithoutEnvironment(env: NodeJS.ProcessEnv): void { * slot hands its host's cache servers and tokens whatever the job has, and the * line says so there. A job with a credential reads with the runner's * `op`, or with one installed for the job where the runner has none - * (core/op.ts). A deploy job cannot deploy without the vault, and - * a run of on_push publishes images of the repo's one key (§ 3.8): both fail - * here, in a line that names the credentials missing. So does a job that - * pushes to its repo where the forge does not hand it the App's credentials, - * which it then reads from the vault (`appOf`). + * (core/op.ts), which the caller finds first for a deploy job. A run of + * on_push publishes images of the repo's one key (§ 3.8): it fails here, in a + * line that names the credentials missing, as does a job that joins the + * overlay or pushes to its repo where the forge does not hand it the App's + * credentials, which it then reads from the vault (`appOf`). */ async function vaultFor( ctx: Context, @@ -111,8 +108,9 @@ async function vaultFor( env: NodeJS.ProcessEnv, temp: string, images: boolean, + op?: string, ): Promise { - if (vaultAccess(env)) return vaultOf(ctx, env, await opOf(ctx, env, temp)); + if (vaultAccess(env)) return vaultOf(ctx, env, op ?? (await opOf(ctx, env, temp))); if (PUSHES[options.job]) { try { vaultOf(ctx, env); @@ -152,6 +150,11 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro const vaultName = `${owner}-ci`; const temp = need('RUNNER_TEMP', env); const permissions = PUSHES[options.job]; + const outputs: Record = {}; + const variables: Record = {}; + /** Directories later steps put first on their PATH. */ + const paths: string[] = []; + const plan: Plan = []; const forgeApp = permissions && env.GH_CLIENT_ID && env.GH_PRIVATE_KEY ? appOfForge(ctx, env) : undefined; // A slot of a runner host shares the host's network, which is on the overlay, and a repo slot carries its host's // cache tokens: only a forge runner joins, and only for what it reaches there. @@ -161,13 +164,12 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro options.overlay === 'netbird' && (options.job === 'deploy' || (options.job === 'repo' && cacheHost !== undefined)); // A repo job of a repo that pushes no image reads the vault only to join the overlay. - const reads = options.job === 'repo' ? images || overlay : !forgeApp; - const vault = reads ? await vaultFor(ctx, options, env, temp, images) : undefined; - const outputs: Record = {}; - const variables: Record = {}; - /** Directories later steps put first on their PATH. */ - const paths: string[] = []; - const plan: Plan = []; + // A deploy job's `op` is the playbook's, which reads the stacks' secrets with a token of its own; the job reads the + // vault only to join the overlay. + const op = options.job === 'deploy' ? await opOf(ctx, env, temp) : undefined; + if (op && op !== 'op') paths.push(dirname(op)); + const reads = options.job === 'repo' ? images || overlay : options.job === 'deploy' ? overlay : !forgeApp; + const vault = reads ? await vaultFor(ctx, options, env, temp, images, op) : undefined; const setupKey = overlay && vault ? await vault.read(`op://${vaultName}/netbird/setup-key`) : undefined; if (options.job === 'repo') { @@ -190,17 +192,12 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro ctx.say(`[dry-run] a token of the tenant’s App for ${repository}: ${Object.keys(permissions).join(', ')} write`); if (forgeApp) ctx.say('the tenant’s GitHub App, from the variable GH_CLIENT_ID and the secret GH_PRIVATE_KEY'); } else { - if (!vault) throw new Error('a deploy job reads the vault'); - const sshKey = keyLines(ctx, await vault.read(`op://${vaultName}/deploy-ssh/private key?ssh-format=openssh`)); - // The operations repo's own deploy job has the inventory in its checkout, told as plx tells an operations repo, by - // the root marker of the checkout the step runs in; an app repo's reads it with a token of the App. - if (!(await isOperationsRepo(ctx))) { - const operations = options.operationsRepo || 'operations'; - const app = await appOf(ctx, vault, vaultName); - const token = await mint(ctx, env, { owner, repo: operations, permissions: { contents: 'read' }, ...app }); - if (token) outputs['operations-token'] = token; - else ctx.say(`[dry-run] a token of the tenant’s App that may read ${owner}/${operations}`); - } + // The deploy key is a repository secret of the repo that deploys (§ 3 PLX-Secrets), handed to this step alone. + if (!env.DEPLOY_SSH_KEY) + throw new Error( + 'the deploy job has no deploy key: the step was handed no DEPLOY_SSH_KEY, the repository secret that holds it', + ); + const sshKey = keyLines(ctx, env.DEPLOY_SSH_KEY); const socket = join(temp, 'ssh-agent.sock'); plan.push( run('ssh-agent', ['-a', socket]), @@ -389,11 +386,12 @@ function login(path: string, content: string): Plan { } /** - * A PEM key with its line breaks: a key pasted into a one-line field of the - * vault arrives with spaces in their place, which neither ssh-add nor a signer - * takes. Ends with a newline, which ssh-add needs. Masked line by line as it - * is returned, since the vault masked the key as one line: whatever prints the - * key later, at any verbosity, prints it masked. + * A PEM key with its line breaks: a key pasted into a one-line field, of the + * vault or of a repository secret, arrives with spaces in their place, which + * neither ssh-add nor a signer takes. Ends with a newline, which ssh-add + * needs. Masked line by line as it is returned, since the forge masked the key + * as one line: whatever prints the key later, at any verbosity, prints it + * masked. */ function keyLines(ctx: Context, key: string): string { const k = key.trim(); diff --git a/packages/cli-ci/src/core/vault.ts b/packages/cli-ci/src/core/vault.ts index 6c241660..35be7edf 100644 --- a/packages/cli-ci/src/core/vault.ts +++ b/packages/cli-ci/src/core/vault.ts @@ -6,7 +6,9 @@ // `plx-ci setup` and no other). Where both are present the Connect server // alone: `op` is started without the service account's token, so that no read // spends the account's budget or depends on which of the two `op` prefers. -// Nothing else in plx-ci or plx reads the vault in a job. +// Nothing else in plx-ci or plx reads the vault `-ci` in a job; the +// stacks' secrets are read from the vault `` by the stack playbook that +// `plx deploy` runs, with the deploy job's own read-only token. // // A value read as a secret is masked in the job's log as soon as it is read, // so that nothing the caller prints afterwards can show it. A value read as diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index de6c3f29..378d343a 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -114,7 +114,6 @@ export { type GitFacet, isNotable, isOperations, - isOperationsRepo, type Kind, shortRemote, type Unit, diff --git a/packages/lib/src/model.ts b/packages/lib/src/model.ts index 29078aff..291ec028 100644 --- a/packages/lib/src/model.ts +++ b/packages/lib/src/model.ts @@ -89,21 +89,6 @@ export const listsOperations = (config?: MarkerConfig): boolean => /** The operations repo is the one whose root marker lists the operations template. */ export const isOperations = (dir: Directory): boolean => listsOperations(dir.config); -/** - * Whether the checkout at `dir` is an operations repo: its root marker lists - * the operations template. A marker that is absent or cannot be read as - * configuration makes it none, as the overview has it. - */ -export async function isOperationsRepo(ctx: Context, dir = '.'): Promise { - const text = await ctx.readFile(join(dir, MARKER_FILE)).catch(() => undefined); - if (text === undefined) return false; - try { - return listsOperations(parseMarkerConfig(text)); - } catch { - return false; - } -} - /** * Every unit of a scanned tree, in tree order, as overview labels them. What * a unit is follows from where it is (§ 1.3 PLX), never from what its marker From 1f876672b22b6339b9ba28846e675f716d848f7d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:43:12 +0100 Subject: [PATCH 66/91] The deploy jobs check out their own repo alone and hold the deploy key and the vault token as repository secrets The workflows hand setup DEPLOY_SSH_KEY and the step of plx deploy DEPLOY_VAULT_TOKEN as its OP_SERVICE_ACCOUNT_TOKEN; the CI vault's token reaches setup only to join the overlay. repo-operations renders no plexus_apps, plexus_up or plexus_deploy_root, and names no tag the platform playbook dropped. Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/pipeline.test.ts | 2 +- .../files/.github/workflows/deploy.yml.jinja | 9 +++++++-- .../files/inventory/group_vars/platform.yml.jinja | 7 +------ templates/repo-operations/files/mise.toml.jinja | 4 ++-- templates/repo-operations/template.yml | 2 +- .../files/.github/workflows/on_push.yml.jinja | 14 +++++++------- templates/repo-turbo/template.yml | 2 +- 7 files changed, 20 insertions(+), 20 deletions(-) diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 9adac687..53269cf2 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -291,7 +291,7 @@ test('setup alone is handed the service account token where the repo answers ci_ // The deploy token is the verb's own, and not the CI vault's. for (const name of APP) assert.doesNotMatch( - unhanded[name].text.replace(/^.*DEPLOY_VAULT_TOKEN.*$/m, ''), + unhanded[name].text.replace(/^ *OP_SERVICE_ACCOUNT_TOKEN: .*DEPLOY_VAULT_TOKEN.*$/m, ''), /service.account|OP_SERVICE/i, name, ); diff --git a/templates/repo-operations/files/.github/workflows/deploy.yml.jinja b/templates/repo-operations/files/.github/workflows/deploy.yml.jinja index 012031f2..f3f14990 100644 --- a/templates/repo-operations/files/.github/workflows/deploy.yml.jinja +++ b/templates/repo-operations/files/.github/workflows/deploy.yml.jinja @@ -43,10 +43,12 @@ jobs: env: MISE_SYSTEM_SHIMS_DIR: ${{ runner.temp }}/mise-system-shims run: mise use -g node@24 'npm:@plexus-ms/cli[allow_low_downloads=true]@{% endraw %}{{ _plexus_version }}{% raw %}' 'npm:@plexus-ms/cli-ci[allow_low_downloads=true]@{% endraw %}{{ _plexus_version }}{% raw %}' + # Setup holds the deploy key, a repository secret, in an agent, and reads the vault of the CI only to join the overlay. - id: setup env: GITHUB_TOKEN: ${{ github.token }} - OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} + DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}{% endraw %}{% if ci_overlay == 'netbird' %}{% raw %} + OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}{% endraw %}{% endif %}{% raw %} run: plx-ci setup deploy --overlay {% endraw %}{{ ci_overlay }}{% raw %} # Ansible, at the major the collection is tested with, and the collection plexus.platform at the Plexus version of # the plx above, which plx deploy runs the stack playbook of, with the community.docker its galaxy.yml names where @@ -59,10 +61,13 @@ jobs: env: ANSIBLE_COLLECTIONS_PATH: ${{ runner.temp }}/collections run: ansible-galaxy collection install 'git+https://github.com/plexus-ms/tooling.git#/ansible/platform/,{% endraw %}{{ _plexus_version }}{% raw %}' + # The stack playbook resolves the stacks' secrets with the read-only token of the tenant's vault, the repository + # secret DEPLOY_VAULT_TOKEN, which this step alone holds; the Connect server of a slot reads another vault. - env: ANSIBLE_COLLECTIONS_PATH: ${{ runner.temp }}/collections + OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.DEPLOY_VAULT_TOKEN }} PLX_DRY_RUN: ${{ inputs.dry_run }} - run: plx deploy --environment production --inventory inventory{% endraw %} + run: env -u OP_CONNECT_HOST -u OP_CONNECT_TOKEN plx deploy --environment production{% endraw %} {%- if ci_overlay == 'netbird' %}{% raw %} - if: ${{ always() && steps.setup.outputs.joined == 'true' }} run: sudo netbird down || true{% endraw %} diff --git a/templates/repo-operations/files/inventory/group_vars/platform.yml.jinja b/templates/repo-operations/files/inventory/group_vars/platform.yml.jinja index 55c0feb9..f0d954db 100644 --- a/templates/repo-operations/files/inventory/group_vars/platform.yml.jinja +++ b/templates/repo-operations/files/inventory/group_vars/platform.yml.jinja @@ -1,12 +1,7 @@ # Generated from plexus-ms/tooling, templates/repo-operations. -# What the hosts that run this tenant's apps get; their apps are per host, in host_vars (§ 3 PLX-Platform). +# What the hosts that run this tenant's stacks get; a stack's environment, its host among it, is a file of the stack (§ 3 PLX-Stack). plexus_deploy_user: plexus -plexus_deploy_root: /opt/stacks - -plexus_up: true - -plexus_apps: [] plexus_deploy_pubkey: "{% raw %}{{ lookup('env', 'DEPLOY_PUBKEY') | default('', true) }}{% endraw %}" plexus_ghcr_user: "{% raw %}{{ lookup('env', 'GHCR_USER') | default('', true) }}{% endraw %}" diff --git a/templates/repo-operations/files/mise.toml.jinja b/templates/repo-operations/files/mise.toml.jinja index 9b199397..4d885e5c 100644 --- a/templates/repo-operations/files/mise.toml.jinja +++ b/templates/repo-operations/files/mise.toml.jinja @@ -25,10 +25,10 @@ terraform = "1" # the runner hosts' root, ci/ # hk is absent on a CI runner whose mise installs only the tools a job names. postinstall = "if command -v hk >/dev/null; then hk install --mise; fi" -# A layer's verb passes what follows `--` to ansible-playbook: `mise platform -- --tags apps --limit vm101`. +# A layer's verb passes what follows `--` to ansible-playbook: `mise platform -- --tags caddy --limit vm101`. [tasks.platform] depends = ["collections"] -description = "The platform layer on the app hosts (PLX-Platform): host baseline, deploy user, ingress, secrets, apps; --tags for a part" +description = "The platform layer on the app hosts (PLX-Platform): host baseline, deploy user, ingress, registry login; --tags for a part" run = './ansible-playbookw platform.yml' {% if infrastructure -%} diff --git a/templates/repo-operations/template.yml b/templates/repo-operations/template.yml index 9cf753f8..c45b2569 100644 --- a/templates/repo-operations/template.yml +++ b/templates/repo-operations/template.yml @@ -52,7 +52,7 @@ questions: ci_overlay: type: str - help: "How a deploy of a third-party app reaches its host (§ 8 PLX-Delivery): none, as the inventory names it; netbird, over the tenant's overlay, which a job on the forge's runners joins for its length" + help: "How a deploy of a third-party app reaches its host (§ 8 PLX-Delivery): none, as the host of each environment file names it; netbird, over the tenant's overlay, which a job on the forge's runners joins for its length" choices: - none - netbird diff --git a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja index 14c6ea60..184aca16 100644 --- a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja @@ -148,16 +148,13 @@ jobs: env: MISE_SYSTEM_SHIMS_DIR: ${{ runner.temp }}/mise-system-shims run: mise use -g node@{% endraw %}{{ node_version }}{% raw %} 'npm:@plexus-ms/cli[allow_low_downloads=true]@{% endraw %}{{ _plexus_version }}{% raw %}' 'npm:@plexus-ms/cli-ci[allow_low_downloads=true]@{% endraw %}{{ _plexus_version }}{% raw %}' + # Setup holds the deploy key, a repository secret, in an agent, and reads the vault of the CI only to join the overlay. - id: setup env: - GITHUB_TOKEN: ${{ github.token }}{% endraw %}{% if ci_service_account %}{% raw %} + GITHUB_TOKEN: ${{ github.token }} + DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}{% endraw %}{% if ci_service_account and ci_overlay == 'netbird' %}{% raw %} OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}{% endraw %}{% endif %} run: plx-ci setup deploy --overlay {{ ci_overlay }}{% raw %} - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - repository: ${{ github.repository_owner }}/operations - token: ${{ steps.setup.outputs.operations-token }} - path: operations # Ansible, at the major the collection is tested with, and the collection plexus.platform at the Plexus version of # the plx above, which plx deploy runs the stack playbook of, with the community.docker its galaxy.yml names where # Ansible's own is older: installed outside the checkout as plx is, the collection where the verb's Ansible looks. @@ -169,9 +166,12 @@ jobs: env: ANSIBLE_COLLECTIONS_PATH: ${{ runner.temp }}/collections run: ansible-galaxy collection install 'git+https://github.com/plexus-ms/tooling.git#/ansible/platform/,{% endraw %}{{ _plexus_version }}{% raw %}' + # The stack playbook resolves the stacks' secrets with the read-only token of the tenant's vault, the repository + # secret DEPLOY_VAULT_TOKEN, which this step alone holds; the Connect server of a slot reads another vault. - env: ANSIBLE_COLLECTIONS_PATH: ${{ runner.temp }}/collections - run: plx deploy --inventory operations/inventory{% endraw %} + OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.DEPLOY_VAULT_TOKEN }} + run: env -u OP_CONNECT_HOST -u OP_CONNECT_TOKEN plx deploy{% endraw %} {%- if ci_overlay == 'netbird' %}{% raw %} - if: ${{ always() && steps.setup.outputs.joined == 'true' }} run: sudo netbird down || true{% endraw %} diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index 03ffe30d..7c6a1426 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -74,7 +74,7 @@ questions: ci_overlay: type: str - help: "How a deploy reaches the app hosts (§ 8 PLX-Delivery): none, as the inventory names them; netbird, over the tenant's overlay, which a job on the forge's runners joins for its length" + help: "How a deploy reaches the app hosts (§ 8 PLX-Delivery): none, as the host of each environment file names them; netbird, over the tenant's overlay, which a job on the forge's runners joins for its length" choices: - none - netbird From 35a727c314fac29c04ada2c57aa6badb4cef44b4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:44:39 +0100 Subject: [PATCH 67/91] The stack template's test: a file for each environment the branches deploy, with host, hostname, env and secrets Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/stack.test.ts | 37 +++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/packages/lib/src/stack.test.ts b/packages/lib/src/stack.test.ts index fc79141b..701e3caf 100644 --- a/packages/lib/src/stack.test.ts +++ b/packages/lib/src/stack.test.ts @@ -16,10 +16,10 @@ const servicesOf = async (answers: Record = {}) => { const TAGGED = (app: string) => `ghcr.io/acme/${app}:\${PLEXUS_TAG:?set by the deploy}`; const LOOPBACK = '127.0.0.1:${PLEXUS_LOOPBACK_PORT:?set by the platform playbook}:3000'; -test('a stack is its compose file and its marker, both its own from birth, with nothing run at birth', async () => { +test('a stack is its compose file, its marker and a file for each environment the branches deploy, all its own from birth, with nothing run at birth', async () => { const result = await render(); assert.deepEqual(result.errors, []); - assert.deepEqual(pathsOf(result), ['PLEXUS.md', 'compose.yaml']); + assert.deepEqual(pathsOf(result), ['PLEXUS.md', 'compose.yaml', 'production.yaml', 'staging.yaml']); for (const [path, origin] of result.files) assert.equal(origin.policy, 'born-once', path); assert.deepEqual(result.birth, []); }); @@ -124,13 +124,40 @@ test('an app is named as its directory under apps/ may be, once', async () => { } }); -test('the compose file says it was generated once and is the stack’s own', async () => { +test('the compose file and the environment files say they were generated once and are the stack’s own', async () => { const lines = generatedFrom(await render()); assert.deepEqual( lines.map(([path]) => path), - ['compose.yaml'], + ['compose.yaml', 'production.yaml', 'staging.yaml'], ); - assert.match(lines[0]?.[1] ?? '', /^# Generated from plexus-ms\/tooling, templates\/stack, once:/); + for (const [, line] of lines) assert.match(line, /^# Generated from plexus-ms\/tooling, templates\/stack, once:/); +}); + +/** An environment's file as the template renders it, parsed. */ +const environmentOf = async (name: string, answers: Record = {}) => + parse(textOf(await render(answers), `${name}.yaml`)) as Record; + +test('an environment file names the four keys: the host to replace, a hostname for the first app, no values and no secrets yet', async () => { + for (const [name, hostname] of [ + ['production', 'shop.example.com'], + ['staging', 'shop.staging.example.com'], + ] as const) + assert.deepEqual(await environmentOf(name), { host: 'host.example.com', hostname, env: {}, secrets: {} }, name); + // The first of several apps publishes the port, so it names the stack's hostname. + assert.equal((await environmentOf('staging', { apps: 'admin,shop' })).hostname, 'admin.staging.example.com'); +}); + +test('a stack of no app has no hostname to name, for it has no port: its environment files hold the host alone', async () => { + const result = await renderBundled(['stack'], { tenant: 'acme' }); + for (const name of ['production', 'staging']) + assert.deepEqual(parse(textOf(result, `${name}.yaml`)), { host: 'host.example.com', env: {}, secrets: {} }, name); +}); + +test('the marker says where an environment’s host, hostname, values and secrets go, and that a new environment is a new file', async () => { + const marker = textOf(await render(), 'PLEXUS.md'); + assert.match(marker, /`production\.yaml`/); + assert.match(marker, /`host`/); + assert.match(marker, /`op:\/\/`/); }); test('the marker has no frontmatter, which plx writes, and says how an app joins and how a second stack comes', async () => { From 6dfa69cc118928e9de527372708708b1a9954641 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:44:51 +0100 Subject: [PATCH 68/91] The newborn operations repo's deploy job deploys its stacks from their environment files, with the deploy key a secret of the repo The stand-in playbook takes its host from the file, setup reads nothing from the vault, and the verb has no inventory. Co-Authored-By: Claude Sonnet 5.5 --- newborns/deploy-job.test.ts | 2 +- newborns/repo-operations.test.ts | 52 +++++++++++++++++--------------- 2 files changed, 29 insertions(+), 25 deletions(-) diff --git a/newborns/deploy-job.test.ts b/newborns/deploy-job.test.ts index 868a44aa..945073b5 100644 --- a/newborns/deploy-job.test.ts +++ b/newborns/deploy-job.test.ts @@ -4,7 +4,7 @@ // step that installs plx, with the job's environment and what each step leaves the next (GITHUB_ENV and // GITHUB_PATH) read as the runner reads them. // -// The job holds the deploy key and the operations repo's token and runs nothing of the repo's code, so +// The job holds the deploy key and the vault token of its repo's secrets and runs nothing of the repo's code, so // the repo's own configuration must reach nothing: a repo's author puts into its mise.toml, beside // the pins, everything mise runs or trusts. Each case below is such a repo, and a probe that must not // fire (a file the code would write, a request the setting would send); after the steps `plx`, run as a diff --git a/newborns/repo-operations.test.ts b/newborns/repo-operations.test.ts index a482650a..aac0babe 100644 --- a/newborns/repo-operations.test.ts +++ b/newborns/repo-operations.test.ts @@ -412,7 +412,7 @@ test('the check sets the root up again where what is on disk is no longer what t // --- the job deploy ---------------------------------------------------------------------- -/** The deploy key as the vault holds it: made up. */ +/** The deploy key as the repository secret holds it: made up. */ const DEPLOY_KEY = '-----BEGIN OPENSSH PRIVATE KEY-----\nbmV3Ym9ybi1kZXBsb3kta2V5\n-----END OPENSSH PRIVATE KEY-----'; /** The two stacks of third-party software, each on a host of its own: `broken` cannot pull its image. */ @@ -441,8 +441,8 @@ function stand(bin: string, name: string, script: string): void { } /** - * The tools of a runner that a deploy reaches, as stand-ins on a PATH of their own. `op` answers the deploy key and - * nothing else. + * The tools of a runner that a deploy reaches, as stand-ins on a PATH of their own. `op` answers its version and + * reads nothing: the deploy key is a repository secret, and the stacks of this repo have no secrets. */ function runnerTools(root: string): string { const bin = join(root, 'bin'); @@ -453,7 +453,6 @@ function runnerTools(root: string): string { 'op', `echo "op $*" >> "$LOGS/op" [ "$1" = --version ] && { echo 2.42.0; exit 0; } -[ "$1 $2" = "read op://acme-ci/deploy-ssh/private key?ssh-format=openssh" ] && { printf '%s\\n' '${DEPLOY_KEY.replaceAll('\n', "' '")}'; exit 0; } echo "op: no item $2" >&2; exit 1`, ); // setup starts the agent on a socket and feeds it the key; the stand-ins record both. @@ -464,25 +463,35 @@ echo "op: no item $2" >&2; exit 1`, } /** - * The stack playbook in a collection plexus.platform under `collections`, as the workflow installs it: on each host, - * reached without ssh, it logs the host, the stack, the environment, whether it runs in check mode and the agent it was - * handed, and ends as the playbook's task Result does: `deployed`, `would deploy` in check mode, and a failed pull for - * the stack `broken`. + * The stack playbook in a collection plexus.platform under `collections`, as the workflow installs it: on the host its + * environment's file names, reached without ssh, it logs the host, the stack, the environment named by the file, whether + * it runs in check mode and the agent it was handed, and ends as the playbook's task Result does: `deployed`, `would + * deploy` in check mode, and a failed pull for the stack `broken`. */ function standInCollection(collections: string): void { put(join(collections, 'ansible_collections', 'plexus', 'platform'), { 'galaxy.yml': 'namespace: plexus\nname: platform\nversion: 0.0.0\nreadme: README.md\nauthors: [acme]\n', - 'playbooks/stack.yml': `- name: The stack playbook, stood in for - hosts: all + 'playbooks/stack.yml': `- name: Read the environment's file, as the playbook does + hosts: localhost connection: local gather_facts: false + tasks: + - name: Add the environment's host + ansible.builtin.add_host: + name: "{{ (lookup('ansible.builtin.file', stack_environment_file) | from_yaml).host }}" + groups: stack_host + ansible_connection: local +- name: The stack playbook, stood in for + hosts: stack_host + gather_facts: false vars: - project: "{{ stack_name }}-{{ stack_environment }}" + environment_name: "{{ stack_environment_file | basename | regex_replace('[.]yaml$', '') }}" + project: "{{ stack_name }}-{{ environment_name }}" fails: "{{ stack_name == 'broken' and not ansible_check_mode }}" tasks: - name: Log the run ansible.builtin.set_fact: - logged: "{{ lookup('ansible.builtin.pipe', 'echo ' ~ ([inventory_hostname, stack_name, stack_environment, ansible_check_mode] | join(' ')) ~ ' $SSH_AUTH_SOCK >> $LOGS/ansible') }}" + logged: "{{ lookup('ansible.builtin.pipe', 'echo ' ~ ([inventory_hostname, stack_name, environment_name, ansible_check_mode] | join(' ')) ~ ' $SSH_AUTH_SOCK >> $LOGS/ansible') }}" # As the playbook's own: one debug, failed where the outcome is a failure. - name: Result ansible.builtin.debug: @@ -521,7 +530,7 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa for (const [stack, host] of Object.entries(STACKS)) put(dir, { [`stacks/${stack}/compose.yaml`]: COMPOSE.replace('%STACK%', stack), - [`inventory/host_vars/${host}.yml`]: `plexus_deploy_target: ssh://deploy@${host}\nplexus_apps:\n - name: ${stack}\n`, + [`stacks/${stack}/production.yaml`]: `host: ${host}\n`, }); await assertBuilt(dir); // The stacks are deployable as born and written: plx doctor finds nothing. @@ -551,7 +560,8 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa standInCollection(join(temp, 'collections')); /** The values of the expressions a step's environment holds here. */ const expressions: Record = { - '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}': 'a-service-account-token', + '${{ secrets.DEPLOY_SSH_KEY }}': DEPLOY_KEY, + '${{ secrets.DEPLOY_VAULT_TOKEN }}': 'a-vault-token', '${{ github.token }}': 'a-job-token', '${{ runner.temp }}': temp, }; @@ -578,13 +588,10 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa jobEnv = { ...jobEnv, ...handedOn(files.GITHUB_ENV) }; } // The deploy key is in the agent, the job is logged in to the registry, and the setup step asked the forge for - // nothing and read nothing else. + // nothing and read nothing from the vault. assert.match(readFileSync(join(logs, 'agent'), 'utf8'), /^ssh-agent -a .*ssh-agent\.sock$/m); assert.match(readFileSync(join(logs, 'agent'), 'utf8'), /^ssh-add - 3$/m); - assert.deepEqual(readFileSync(join(logs, 'op'), 'utf8').trim().split('\n'), [ - 'op --version', - 'op read op://acme-ci/deploy-ssh/private key?ssh-format=openssh', - ]); + assert.deepEqual(readFileSync(join(logs, 'op'), 'utf8').trim().split('\n'), ['op --version']); assert.equal(existsSync(join(logs, 'curl')), false, 'the operations repo’s setup asks the forge for nothing'); assert.deepEqual(handedOn(files.GITHUB_OUTPUT), {}, 'it mints no token for another repo'); assert.match(jobEnv.SSH_AUTH_SOCK ?? '', /ssh-agent\.sock$/); @@ -592,7 +599,7 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa /** The verb step of the workflow, run as the forge runs it: its command, and its environment with the input `dry_run` given as `input`. */ const verb = async (input: string) => { - const step = steps.find((s) => /\bdeploy --environment production --inventory inventory$/.test(s.run ?? '')); + const step = steps.find((s) => /\bplx deploy --environment production$/.test(s.run ?? '')); assert.ok(step?.run, 'the workflow has the verb step'); const env = envOf(step, { '${{ inputs.dry_run }}': input }); return tryRun('mise', ['exec', '--', ...step.run.split(' ')], dir, { ...jobEnv, ...env }); @@ -604,10 +611,7 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa /** A run's line in the log: the host, the stack, production, check mode or not, and the agent setup handed on. */ const expect = (stack: keyof typeof STACKS, check: string) => `${STACKS[stack]} ${stack} production ${check} ${jobEnv.SSH_AUTH_SOCK}`; - const BLOCKS = [ - 'broken-production → ssh://deploy@broken.example.internal', - 'good-production → ssh://deploy@good.example.internal', - ]; + const BLOCKS = ['broken-production → broken.example.internal', 'good-production → good.example.internal']; // The dry run: the playbook's own, in check mode, for both stacks. const dry = await verb('true'); From ee909ccc6bf6a21807df4e6652026e7bfa011874 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:45:30 +0100 Subject: [PATCH 69/91] The newborn repo's test lists the environment files of its stack, which the doctor passes as born Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/newSite.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index 3fcbf9eb..a2f95eb3 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -409,7 +409,7 @@ test('a repo from repo-turbo with updates beside it, an app from app-nextjs and ]); const stack = await nested(join(target, 'stack'), ['stack'], { apps: 'web' }); - assert.deepEqual(stack.files, ['PLEXUS.md', 'compose.yaml']); + assert.deepEqual(stack.files, ['PLEXUS.md', 'compose.yaml', 'production.yaml', 'staging.yaml']); assert.match(text(target, 'stack/PLEXUS.md'), /^---\ntemplates: \[stack\]\nprofile: stateless\n---\n\n/); assert.match( text(target, 'stack/compose.yaml'), From 7867126ec28ef2482014e528a0d7851b8b1cddec Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:45:51 +0100 Subject: [PATCH 70/91] The template stack renders a file for each environment the branches deploy: host, hostname, env and secrets Co-Authored-By: Claude Sonnet 5.5 --- templates/stack/files/PLEXUS.md.jinja | 3 +++ templates/stack/files/production.yaml.jinja | 9 +++++++++ templates/stack/files/staging.yaml.jinja | 9 +++++++++ templates/stack/template.yml | 10 +++++++--- 4 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 templates/stack/files/production.yaml.jinja create mode 100644 templates/stack/files/staging.yaml.jinja diff --git a/templates/stack/files/PLEXUS.md.jinja b/templates/stack/files/PLEXUS.md.jinja index 7bbb5ac1..9a0a36a5 100644 --- a/templates/stack/files/PLEXUS.md.jinja +++ b/templates/stack/files/PLEXUS.md.jinja @@ -4,6 +4,9 @@ - Born with no app of the repo, its compose file holds `services: {}`, which `plx doctor` reports until the services of the software it runs are written. {%- endif %} - An app joins it by a service whose image is `//:${PLEXUS_TAG:?set by the deploy}`, which loads `.env` and `.env.secret` (optional) and declares a healthcheck; one service of the stack publishes `PLEXUS_LOOPBACK_PORT`. +- Each environment is a file beside the compose file, named after it: `production.yaml` and `staging.yaml` are born with the stack, and a further environment is a further file. + Its `host` is where it deploys, `[user@]address[:port]`, and replacing the placeholder is the first thing to do; its `hostname` is the public name the proxy serves, which the service that publishes the loopback port needs. + Its `env` holds the plain values the compose file reads, and its `secrets` the same kind of names as `op://` pointers, which the deploy resolves; every environment lists the same names. - A second stack in the repo moves `stack/` to `stacks//` and is created beside it with `plx new stacks/ stack -a apps=`. {%- if profile == 'stateful' %} - Its `migrate` service runs the migration on the image of the app that carries it, whose marker answers `migrates: true`, before every deploy brings the stack up; software the tenant does not build that migrates itself lists `PLX-Stack/Stateful/MigrateService` under `deviations` instead. diff --git a/templates/stack/files/production.yaml.jinja b/templates/stack/files/production.yaml.jinja new file mode 100644 index 00000000..963c80dd --- /dev/null +++ b/templates/stack/files/production.yaml.jinja @@ -0,0 +1,9 @@ +{%- set names = apps.split(',') | map('trim') | reject('equalto', '') | list -%} +# Generated from plexus-ms/tooling, templates/stack, once: the environment `production` of this stack (PLX-Stack), its own from then on. +# Replace `host` (`[user@]address[:port]`); list the values the compose file reads under `env` and each secret, an `op://` pointer, under `secrets`. +host: host.example.com +{%- if names %} +hostname: {{ names[0] }}.example.com +{%- endif %} +env: {} +secrets: {} diff --git a/templates/stack/files/staging.yaml.jinja b/templates/stack/files/staging.yaml.jinja new file mode 100644 index 00000000..2bd1dd7d --- /dev/null +++ b/templates/stack/files/staging.yaml.jinja @@ -0,0 +1,9 @@ +{%- set names = apps.split(',') | map('trim') | reject('equalto', '') | list -%} +# Generated from plexus-ms/tooling, templates/stack, once: the environment `staging` of this stack (PLX-Stack), its own from then on. +# Replace `host` (`[user@]address[:port]`); list the values the compose file reads under `env` and each secret, an `op://` pointer, under `secrets`. +host: host.example.com +{%- if names %} +hostname: {{ names[0] }}.staging.example.com +{%- endif %} +env: {} +secrets: {} diff --git a/templates/stack/template.yml b/templates/stack/template.yml index d679d0f3..7204b384 100644 --- a/templates/stack/template.yml +++ b/templates/stack/template.yml @@ -1,5 +1,6 @@ # One stack (PLX-Stack), rendered at stack/ in a repo with one stack and at stacks// in a repo with several: -# its compose file and its marker. Its name is its directory's, or at stack/ the repo's, so no question asks it. +# its compose file, its marker and the file of each environment the branches deploy today. +# Its name is its directory's, or at stack/ the repo's, so no question asks it. name: stack # The enclosing repo's answer; whoever renders the stack passes it. @@ -46,7 +47,10 @@ questions: ghcr.io/acme: lowercase letters, digits, ., _, - and :, in two or more parts parted by /{% endif %} policies: - # Both files are the stack's own from birth and never re-synced: the services of the compose file are the - # person's, the marker's body is the stack's prose, and its frontmatter is plx's. + # Every file is the stack's own from birth and never re-synced: the services of the compose file are the + # person's, the marker's body is the stack's prose, its frontmatter is plx's, and an environment's file holds the + # person's host, values and pointers. PLEXUS.md.jinja: born-once compose.yaml.jinja: born-once + production.yaml.jinja: born-once + staging.yaml.jinja: born-once From 40200abdbb3cdf6bd97bd2973e76d1b10a61420b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:46:58 +0100 Subject: [PATCH 71/91] The operations repo's marker says plx deploy takes each stack's environment file, with no inventory Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/repoOperations.test.ts | 2 ++ templates/repo-operations/files/PLEXUS.md.jinja | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/lib/src/repoOperations.test.ts b/packages/lib/src/repoOperations.test.ts index d93ca004..dae485e7 100644 --- a/packages/lib/src/repoOperations.test.ts +++ b/packages/lib/src/repoOperations.test.ts @@ -127,6 +127,8 @@ test('the marker is written once, and without frontmatter, which plx writes', as assert.match(textOf(result, 'PLEXUS.md'), /^- The operations repo of `acme`/); // Third-party software is stacks of no app, as plx deploy reads them; nothing is under apps/. assert.match(textOf(result, 'PLEXUS.md'), /`stacks\/\/`.*`stack\/`/); + assert.match(textOf(result, 'PLEXUS.md'), /plx deploy --environment `.*a file for that environment/); + assert.doesNotMatch(textOf(result, 'PLEXUS.md'), /--inventory/); assert.doesNotMatch(textOf(result, 'PLEXUS.md'), /apps\//); // And what a person adds to the compose file plx new gives such a stack, so that plx doctor passes. for (const needed of [ diff --git a/templates/repo-operations/files/PLEXUS.md.jinja b/templates/repo-operations/files/PLEXUS.md.jinja index 60f8dcfd..8396c2e7 100644 --- a/templates/repo-operations/files/PLEXUS.md.jinja +++ b/templates/repo-operations/files/PLEXUS.md.jinja @@ -1,7 +1,7 @@ -- The operations repo of `{{ tenant }}`: the playbooks that mount the `plexus.*` collections, one per layer, the inventory they run on, and the third-party software it operates, as stacks of no app: each at `stacks//`, or at `stack/` where there is one, created by `plx new` from the template `stack`, with a marker of its own. +- The operations repo of `{{ tenant }}`: the playbooks that mount the `plexus.*` collections, one per layer, the inventory of the hosts they run on, and the third-party software it operates, as stacks of no app: each at `stacks//`, or at `stack/` where there is one, created by `plx new` from the template `stack`, with a marker of its own. - `plx new stacks/ stack` gives a stack of third-party software a compose file of `services: {}` (`plx new stack stack` for the one stack of a repo that has one, which also needs `repo` in this marker, the repo's name). For `plx doctor` to pass, add its services, each with its image pinned and the label `plexus.tenant: {{ tenant }}`. The service that serves it publishes `127.0.0.1:${PLEXUS_LOOPBACK_PORT:?set by the platform playbook}:`, as the one port of the stack, declares a healthcheck, and loads under `env_file` both `.env` and `.env.secret`, the latter with `required: false`. -- `plx deploy --environment --inventory inventory` deploys every stack with a record in that environment; the workflow `deploy` does it into production. +- `plx deploy --environment ` deploys every stack that has a file for that environment, to the host the file names; the workflow `deploy` does it into production. - `mise :platform` applies the platform layer{% if infrastructure %}, `mise :infrastructure` the infrastructure layer{% endif %}; `mise :check` checks the repo and `mise :test` runs check first. - The Plexus version the repo is on is the `version` of this marker, and its `plx` pin in `mise.toml` follows it, the collections in `requirements.yml` pinned to the same. From 9bdbb689c533ca8f34e771975dc7415bd38992f7 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:08:20 +0100 Subject: [PATCH 72/91] The newborn operations repo's stacks name a hostname in both environment files, as the doctor asks Co-Authored-By: Claude Sonnet 5.5 --- newborns/repo-operations.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/newborns/repo-operations.test.ts b/newborns/repo-operations.test.ts index aac0babe..78e73dc0 100644 --- a/newborns/repo-operations.test.ts +++ b/newborns/repo-operations.test.ts @@ -530,7 +530,8 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa for (const [stack, host] of Object.entries(STACKS)) put(dir, { [`stacks/${stack}/compose.yaml`]: COMPOSE.replace('%STACK%', stack), - [`stacks/${stack}/production.yaml`]: `host: ${host}\n`, + [`stacks/${stack}/production.yaml`]: `host: ${host}\nhostname: ${stack}.example.com\n`, + [`stacks/${stack}/staging.yaml`]: `host: ${host}\nhostname: ${stack}.staging.example.com\n`, }); await assertBuilt(dir); // The stacks are deployable as born and written: plx doctor finds nothing. From d177671c9048eea4d7d4d00541ea34d56fa23f02 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:12:14 +0100 Subject: [PATCH 73/91] The stack playbook's test drops every secret, and reads one that is empty or does not answer An environment whose last secret is dropped deploys, under --check too: .env.secret stays, empty and 0600, the services that loaded it are re-created, and a second run changes nothing. A value the vault holds empty is refused, naming the pointer; a read that does not answer within stack_secret_timeout is refused, naming the usual cause, and leaves no op running. The vault CLI's stand-in waits for a pointer ending in /locked. Co-Authored-By: Claude Opus 5.5 --- tests/stack-playbook.sh | 42 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/tests/stack-playbook.sh b/tests/stack-playbook.sh index c4d07acc..1ff09961 100755 --- a/tests/stack-playbook.sh +++ b/tests/stack-playbook.sh @@ -73,10 +73,12 @@ fail() { } # The vault's CLI as the playbook calls it: `op read --no-newline op://` -# prints the file $work/vault/ as it is. +# prints the file $work/vault/ as it is; a path ending in /locked waits, +# as op does for an unlock nobody answers. cat >"$work/bin/op" <<'EOF' #!/bin/sh [ "$1 $2" = 'read --no-newline' ] || { echo "op: the stand-in reads, with --no-newline, and does not $*" >&2; exit 2; } +case $3 in */locked) exec sleep 599 ;; esac [ -f "$VAULT/${3#op://}" ] || { echo "[ERROR] could not read secret '$3': no such item" >&2; exit 1; } cat "$VAULT/${3#op://}" EOF @@ -441,7 +443,7 @@ done [ "$(image_of staging web)" = "$web_v2" ] || fail "web does not run $web_v2" echo "✓ $case" -case='a secret that cannot be read' +case='a secret that cannot be read, is empty, or does not answer' snapshot() { find "$stacks/$run-shop-staging" -type f -exec sha256sum {} + | sort; } before=$(snapshot) environment staging 'env:' ' GREETING: hello' 'secrets:' ' DB_PASSWORD: op://acme/shop/staging/missing' @@ -450,6 +452,20 @@ deploy staging "$work/no-worker.yaml" [[ $line == "$run-shop-staging: failed: "*"the secret DB_PASSWORD (op://acme/shop/staging/missing) could not be read: "*"no such item" ]] || fail "last line: $line" [ "$(snapshot)" = "$before" ] || fail "a file of the environment changed" +secret op://acme/shop/staging/empty '' +environment staging 'env:' ' GREETING: hello' 'secrets:' ' DB_PASSWORD: op://acme/shop/staging/empty' +deploy staging "$work/no-worker.yaml" +[ "$status" != 0 ] || fail "an empty secret: exit code 0" +[ "$line" = "$run-shop-staging: failed: 'Check that every secret was read' failed: the secret DB_PASSWORD (op://acme/shop/staging/empty) is empty in the vault" ] || + fail "an empty secret: last line: $line" +[ "$(snapshot)" = "$before" ] || fail "an empty secret: a file of the environment changed" +environment staging 'env:' ' GREETING: hello' 'secrets:' ' DB_PASSWORD: op://acme/shop/staging/locked' +deploy staging "$work/no-worker.yaml" -e stack_secret_timeout=2 +[ "$status" != 0 ] || fail "a read that does not answer: exit code 0" +[[ $line == "$run-shop-staging: failed: "*"the secret DB_PASSWORD (op://acme/shop/staging/locked) could not be read: op read did not answer within 2 seconds"*unlock* ]] || + fail "a read that does not answer: last line: $line" +[ "$(snapshot)" = "$before" ] || fail "a read that does not answer: a file of the environment changed" +! pgrep -f 'sleep 599' >/dev/null || fail "the read that did not answer is still running" echo "✓ $case" case='a deploy of the files in place that fails' @@ -468,6 +484,28 @@ deploy staging "$work/no-worker.yaml" docker run --rm --name "$run-probe" -v "$run-shop-staging_data:/data" busybox:1.37 sh -c 'echo ran >> /data/migrated' echo "✓ $case" +case='an environment whose secrets are all dropped' +# .env.secret stays, empty: the services that loaded it are re-created without +# the values. +web_id=$(container staging web) +environment staging 'env:' ' GREETING: hello' " ODD: '${value//\'/\'\'}'" +deploy staging "$work/no-worker.yaml" --check --diff +[ "$status" = 0 ] || fail "a dry run: exit code $status" +[ "$line" = "$run-shop-staging: would deploy" ] || fail "a dry run: last line: $line" +deploy staging "$work/no-worker.yaml" +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-shop-staging: deployed" ] || fail "last line: $line" +[ -f "$stacks/$run-shop-staging/.env.secret" ] && [ ! -s "$stacks/$run-shop-staging/.env.secret" ] || fail ".env.secret is not there and empty" +[ "$(stat -c %a "$stacks/$run-shop-staging/.env.secret")" = 600 ] || fail ".env.secret is not 0600" +[ "$(container staging web)" != "$web_id" ] || fail "web was not re-created" +[ -z "$(value_of staging API_TOKEN)" ] || fail "web still sees API_TOKEN" +[ "$(health_of staging web)" = healthy ] || fail "web is not healthy" +deploy staging "$work/no-worker.yaml" +[ "$line" = "$run-shop-staging: unchanged" ] || fail "run again: last line: $line" +deploy staging "$work/no-worker.yaml" --check +[ "$line" = "$run-shop-staging: unchanged" ] || fail "a dry run, run again: last line: $line" +echo "✓ $case" + case='a first deploy whose migrate fails, beside a container of the project' environment stray printf 'services:\n stray:\n image: %s\n init: true\n command: ["sleep", "3600"]\n' "$worker" >"$work/stray.yaml" From 2da179463a4759e6a78f1e8967a7db18cb21dd34 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:12:28 +0100 Subject: [PATCH 74/91] The stack playbook writes an empty .env.secret, refuses an empty secret, and gives op read a timeout The template lookup gives none rather than an empty string for an environment without secrets, so writing .env.secret after the last secret was dropped failed, and the dry run's undo failed with it: the text is now an empty string, and a dry run, which wrote nothing, undoes nothing. Each op read runs under the Python that runs Ansible, which kills op after stack_secret_timeout seconds (30) and says that it mostly waits for an unlock nobody answers; a value the vault holds empty is refused. Co-Authored-By: Claude Opus 5.5 --- .../platform/roles/stack/defaults/main.yml | 5 +++ .../roles/stack/tasks/environment.yml | 32 ++++++++++++++++--- ansible/platform/roles/stack/tasks/main.yml | 7 ++-- 3 files changed, 36 insertions(+), 8 deletions(-) diff --git a/ansible/platform/roles/stack/defaults/main.yml b/ansible/platform/roles/stack/defaults/main.yml index b52e972a..af79400c 100644 --- a/ansible/platform/roles/stack/defaults/main.yml +++ b/ansible/platform/roles/stack/defaults/main.yml @@ -18,6 +18,11 @@ stack_root: /opt/stacks # lowest that no other environment on the host holds, taken once and kept. stack_port_range: 20000-20999 +# How long, in seconds, each `op read` may take where the playbook runs +# before the deploy fails; a read that hangs waits mostly for an unlock +# nobody answers. +stack_secret_timeout: 30 + # How long, in seconds, the deploy waits for every service that declares a # healthcheck to turn healthy: the whole wait, which a healthcheck's # start_period does not extend. diff --git a/ansible/platform/roles/stack/tasks/environment.yml b/ansible/platform/roles/stack/tasks/environment.yml index c3179719..09f0027c 100644 --- a/ansible/platform/roles/stack/tasks/environment.yml +++ b/ansible/platform/roles/stack/tasks/environment.yml @@ -54,10 +54,24 @@ # Each pointer resolved where the playbook runs, by the vault's CLI and the # session or token it finds there; the value as the vault holds it, a # trailing newline included. Read in a dry run too, to tell whether - # .env.secret would change. + # .env.secret would change. Each read is given stack_secret_timeout seconds + # by the Python that runs Ansible, which kills op where it does not answer + # and exits 124. - name: Resolve the secrets ansible.builtin.command: - argv: [op, read, --no-newline, "{{ item.value }}"] + argv: + - "{{ ansible_playbook_python }}" + - -c + - | + import subprocess, sys + try: + sys.exit(subprocess.run(['op', 'read', '--no-newline', sys.argv[2]], timeout=float(sys.argv[1])).returncode) + except subprocess.TimeoutExpired: + sys.exit(124) + except FileNotFoundError: + sys.exit('op, the vault\'s CLI, is not on the PATH') + - "{{ stack_secret_timeout }}" + - "{{ item.value }}" strip_empty_ends: false loop: "{{ stack_file.secrets | default({}, true) | dict2items }}" register: stack_reads @@ -66,14 +80,22 @@ check_mode: false no_log: true + # A value that is empty in the vault is refused: it is never a secret, and + # mostly a field that was never filled. The line names the pointer, never + # a value. - name: Check that every secret was read - when: stack_failed_reads | length > 0 + when: (stack_failed_reads + stack_empty_reads) | length > 0 vars: stack_failed_reads: "{{ stack_reads.results | default([]) | rejectattr('rc', 'equalto', 0) | list }}" + stack_empty_reads: "{{ stack_reads.results | default([]) | selectattr('rc', 'equalto', 0) | selectattr('stdout', 'equalto', '') | list }}" + stack_failed: "{{ (stack_failed_reads + stack_empty_reads) | first }}" ansible.builtin.fail: msg: >- - the secret {{ stack_failed_reads[0].item.key }} ({{ stack_failed_reads[0].item.value }}) could not be read: - {{ (stack_failed_reads[0].stderr | default('', true) or stack_failed_reads[0].msg | default('no message')).splitlines() | last }} + the secret {{ stack_failed.item.key }} ({{ stack_failed.item.value }}) + {{ 'is empty in the vault' if stack_failed.rc == 0 + else ('could not be read: op read did not answer within ' ~ stack_secret_timeout ~ ' seconds, mostly because it waits' + ~ ' for an unlock nobody answers: a locked app or an expired session where it runs') if stack_failed.rc == 124 + else ('could not be read: ' ~ (stack_failed.stderr | default('', true) or stack_failed.msg | default('no message')).splitlines() | last) }} - name: Add the environment's host vars: diff --git a/ansible/platform/roles/stack/tasks/main.yml b/ansible/platform/roles/stack/tasks/main.yml index e4bfa76f..f80dc229 100644 --- a/ansible/platform/roles/stack/tasks/main.yml +++ b/ansible/platform/roles/stack/tasks/main.yml @@ -57,9 +57,10 @@ | combine({'PLEXUS_LOOPBACK_PORT': stack_route.stdout | regex_findall('port=([0-9]+)') | first} if stack_route is not skipped else {})}) }} + # The lookup gives no string, but none, for an environment without secrets. - name: Render .env.secret ansible.builtin.set_fact: - stack_secret_text: "{{ lookup('ansible.builtin.template', 'dotenv.j2', template_vars={'variables': stack_secrets}) }}" + stack_secret_text: "{{ lookup('ansible.builtin.template', 'dotenv.j2', template_vars={'variables': stack_secrets}) or '' }}" no_log: true - name: Look for the files in place @@ -191,9 +192,9 @@ # file the run replaced from its previous copy, and one it created removed. # After a first deploy, to no compose.yaml: its containers and networks go, # its volumes stay, and .env and .env.secret stay with the port the route - # names. + # names. A dry run has written nothing to undo. - name: Undo the writes - when: stack_written | default([]) | length > 0 + when: stack_written | default([]) | length > 0 and not ansible_check_mode block: - name: Restore the files the run replaced when: stack_existed['compose.yaml'] and stack_existed[item] From 8ab900691b79839ff3a1cfbb78c5ca587a23e959 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:46:44 +0100 Subject: [PATCH 75/91] The stack playbook's test narrows a run, and ends a host or hostname with a line break A run given --limit, --tags or --skip-tags fails with a Result line that says the playbook takes none of them, since each leaves out the deploy or the line that says how it ended. A host or a hostname whose text ends in a line break is refused with the environment's file. Co-Authored-By: Claude Opus 5.5 --- tests/stack-playbook.sh | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/tests/stack-playbook.sh b/tests/stack-playbook.sh index 1ff09961..b96c7ceb 100755 --- a/tests/stack-playbook.sh +++ b/tests/stack-playbook.sh @@ -271,7 +271,8 @@ hostname: "qa.example.com {"' 'host: localhost env: {PLEXUS_LOOPBACK_PORT: "3000"}' 'host: localhost env: {TOKEN: a} secrets: {TOKEN: op://acme/shop/qa/token}' 'host: localhost -domain: qa.example.com' '- host: localhost'; do +domain: qa.example.com' '- host: localhost' 'host: "localhost\n"' 'host: localhost +hostname: "qa.example.com\n"'; do printf '%s\n' "$file" >"$work/env/qa.yaml" deploy qa "$work/v1.yaml" [ "$status" != 0 ] || fail "$file: exit code 0" @@ -281,6 +282,16 @@ domain: qa.example.com' '- host: localhost'; do done echo "✓ $case" +case='a run narrowed by --limit, --tags or --skip-tags' +# Each would leave out the deploy, or the line that says how it ended. +for narrowed in '--limit localhost' '--tags deploy' '--skip-tags deploy'; do + deploy staging "$work/v2.yaml" $narrowed + [ "$status" != 0 ] || fail "$narrowed: exit code 0" + [ "$line" = "the stack: failed: 'Check the arguments' failed: the stack playbook takes no --limit, --tags or --skip-tags; it deploys the environment's file whole" ] || + fail "$narrowed: last line: $line" +done +echo "✓ $case" + case='a dry run (--check)' web_id=$(container staging web) worker_id=$(container staging worker) cp "$stacks/$run-shop-staging/compose.yaml.prev" "$work/prev.yaml" From a4fde3c281162f0c14912799bec56e83b0200b25 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:47:00 +0100 Subject: [PATCH 76/91] The stack playbook refuses a narrowed run, and a host or hostname ending in a line break Every task is tagged always, so that the first, a check of the arguments, runs under --tags too, and refuses a --limit, --tags or --skip-tags with a Result line: each would leave out the deploy, or the line that says how it ended. The forms of host and hostname end in \Z, where $ let a trailing line break pass, and the route script's arguments are quoted. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/playbooks/stack.yml | 4 +++- ansible/platform/roles/stack/tasks/environment.yml | 11 +++++++++++ ansible/platform/roles/stack/tasks/main.yml | 2 +- ansible/platform/roles/stack/vars/main.yml | 7 ++++--- 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/ansible/platform/playbooks/stack.yml b/ansible/platform/playbooks/stack.yml index cf5efcbc..4b5d7161 100644 --- a/ansible/platform/playbooks/stack.yml +++ b/ansible/platform/playbooks/stack.yml @@ -122,6 +122,8 @@ ansible.builtin.include_role: name: plexus.platform.stack tasks_from: environment.yml + apply: { tags: [always] } + tags: [always] - name: Deploy one environment of a stack hosts: stack_host @@ -129,4 +131,4 @@ vars_files: - ../roles/ingress/defaults/main.yml # ingress_fragments_dir roles: - - { role: plexus.platform.stack } + - { role: plexus.platform.stack, tags: [always] } diff --git a/ansible/platform/roles/stack/tasks/environment.yml b/ansible/platform/roles/stack/tasks/environment.yml index 09f0027c..ffb3b7ac 100644 --- a/ansible/platform/roles/stack/tasks/environment.yml +++ b/ansible/platform/roles/stack/tasks/environment.yml @@ -4,6 +4,17 @@ # added to the group stack_host with what the deploy there reads. - name: Read the environment block: + # The run is whole and its one host the file's: a --limit or a tag would + # leave out the deploy, or the line that says how it ended. + - name: Check the arguments + ansible.builtin.assert: + that: + - ansible_limit is not defined + - ansible_run_tags | list == ['all'] + - ansible_skip_tags | length == 0 + fail_msg: the stack playbook takes no --limit, --tags or --skip-tags; it deploys the environment's file whole + quiet: true + - name: Check the variables ansible.builtin.assert: that: diff --git a/ansible/platform/roles/stack/tasks/main.yml b/ansible/platform/roles/stack/tasks/main.yml index f80dc229..61ad8900 100644 --- a/ansible/platform/roles/stack/tasks/main.yml +++ b/ansible/platform/roles/stack/tasks/main.yml @@ -28,7 +28,7 @@ when: stack_hostname | length > 0 ansible.builtin.script: cmd: >- - route.sh {{ stack_root | quote }} {{ ingress_fragments_dir | quote }} {{ stack_project }} {{ stack_hostname }} + route.sh {{ stack_root | quote }} {{ ingress_fragments_dir | quote }} {{ stack_project | quote }} {{ stack_hostname | quote }} {{ stack_port_range | quote }} {{ 'check' if ansible_check_mode else '' }} register: stack_route changed_when: "'route=changed' in stack_route.stdout" diff --git a/ansible/platform/roles/stack/vars/main.yml b/ansible/platform/roles/stack/vars/main.yml index 16a1d671..8beb1432 100644 --- a/ansible/platform/roles/stack/vars/main.yml +++ b/ansible/platform/roles/stack/vars/main.yml @@ -1,11 +1,12 @@ --- -# The forms tasks/environment.yml holds an environment's file to. +# The forms tasks/environment.yml holds an environment's file to, each ending +# in \Z, the end of the text, where $ would let a trailing line break pass. # host: [user@]address[:port], an IPv6 address in brackets where a port # follows; the groups are the user, a bracketed address, its port, an address # without a colon, its port, and a bare IPv6 address. stack_host_form: "^(?:([A-Za-z0-9_][A-Za-z0-9._-]*)@)?\ (?:\\[([0-9A-Fa-f:.]+)\\](?::([0-9]+))?\ |([A-Za-z0-9][A-Za-z0-9.-]*)(?::([0-9]+))?\ - |([0-9A-Fa-f.]*:[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*))$" + |([0-9A-Fa-f.]*:[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*))\\Z" # hostname, lowercased: a DNS name, labels of letters, digits and -. -stack_hostname_form: '^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)*[a-z0-9]([a-z0-9-]*[a-z0-9])?$' +stack_hostname_form: '^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)*[a-z0-9]([a-z0-9-]*[a-z0-9])?\Z' From 7ffa5d5bc0e335bb7ee3d86a49e58991452e1ed3 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:47:17 +0100 Subject: [PATCH 77/91] The stack playbook's test claims a port something listens on, and a hostname of an earlier version's routes The prepared host carries a route of an earlier version in apps.caddy, as a host in migration does. A new environment claiming its hostname ends refused with the proxy's own reason, its fragment gone and nothing else written; an environment whose fragment changes to it ends with the fragment as it was. A port of the range that something on the host listens on is skipped. A fragment that does not parse gives caddy validate's reason. Co-Authored-By: Claude Opus 5.5 --- tests/stack-playbook.sh | 50 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/tests/stack-playbook.sh b/tests/stack-playbook.sh index b96c7ceb..c06fcc58 100755 --- a/tests/stack-playbook.sh +++ b/tests/stack-playbook.sh @@ -633,13 +633,17 @@ status=0 timeout 600 ansible-playbook -i "$work/host.yml" --tags platform --skip-tags caddy plexus.platform.playbook "$work/out" 2>&1 || status=$? [ "$status" = 0 ] || fail "the platform playbook: exit code $status" # Beyond what the platform playbook does: this daemon's socket for the deploy -# user, in place of a daemon of the host's own, and the proxy on 127.0.0.1 and -# the run's ports, with certificates from its own CA. +# user, in place of a daemon of the host's own; the proxy on 127.0.0.1 and the +# run's ports, with certificates from its own CA; and a route of an earlier +# version, in /etc/caddy/apps.caddy as a host in migration has it, which the +# root imports as the ingress role writes it where the file is there. gid=$(stat -c %g /var/run/docker.sock) on sh -c "ln -s /docker.sock /run/docker.sock && { getent group $gid >/dev/null || groupadd -g $gid docker; } && usermod -aG \$(getent group $gid | cut -d: -f1) plexus" on sh -c "printf '{\n\thttp_port $http\n\thttps_port $https\n\tdefault_bind 127.0.0.1\n\tlocal_certs\n\tskip_install_trust\n}\n' | - cat - /etc/caddy/Caddyfile >/etc/caddy/Caddyfile.run && mv /etc/caddy/Caddyfile.run /etc/caddy/Caddyfile && systemctl reload caddy" || + cat - /etc/caddy/Caddyfile >/etc/caddy/Caddyfile.run && mv /etc/caddy/Caddyfile.run /etc/caddy/Caddyfile" && + printf 'legacy.example.com {\n\trespond "legacy"\n}\n' | docker exec -i "$host" sh -c 'cat >/etc/caddy/apps.caddy' && + on sed -i 's|^import /etc/caddy/stacks/|import /etc/caddy/apps*.caddy\n&|' /etc/caddy/Caddyfile && on systemctl reload caddy || fail "the proxy does not take the run's ports" echo "✓ $case" @@ -761,12 +765,50 @@ deploy_on "$run-docs" qa -e stack_port_range="$first-$first" on test ! -e "/etc/caddy/stacks/$run-docs-qa.caddy" || fail "a fragment was written" echo "✓ $case" +case='a port of the range that something on the host listens on' +docker run -d --rm --name "$run-listener" --network host busybox:1.37 httpd -f -p "127.0.0.1:$((first + 3))" >/dev/null +for _ in $(seq 50); do curl -s -o /dev/null -m 1 "http://127.0.0.1:$((first + 3))/" && break; sleep 0.2; done +site "$run-docs" listened 'hostname: listened.docs.example.com' 'env:' ' GREETING: docs listened' +deploy_on "$run-docs" listened +docker rm -f "$run-listener" >/dev/null +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-docs-listened: deployed" ] || fail "last line: $line" +[ "$(port_of "$run-docs-listened")" = "$((first + 4))" ] || fail "the port is $(port_of "$run-docs-listened"), not $((first + 4))" +[ "$(get listened.docs.example.com /)" = 'docs listened 200' ] || fail "the route: $(get listened.docs.example.com /)" +echo "✓ $case" + +case='a hostname the routes of an earlier version serve' +# The new environment's: refused by the proxy, its fragment gone and nothing +# else written; an environment's fragment that changes to it: put back as it was. +site "$run-docs" older 'hostname: legacy.example.com' 'env:' ' GREETING: docs older' +deploy_on "$run-docs" older +[ "$status" != 0 ] || fail "a new environment: exit code 0" +[[ $line == "$run-docs-older: failed: "*"the proxy refused to reload with the route of legacy.example.com, which is as it was: caddy validate says "*legacy.example.com* ]] || + fail "a new environment: last line: $line" +on test ! -e "/etc/caddy/stacks/$run-docs-older.caddy" || fail "a new environment: the refused fragment is still there" +on test ! -e "/opt/stacks/$run-docs-older" || fail "a new environment: the directory was laid out" +[ "$(get legacy.example.com /)" = 'legacy 200' ] || fail "the earlier version's route: $(get legacy.example.com /)" +fragment_before=$(on cat "/etc/caddy/stacks/$run-shop-staging.caddy") env_before=$(on cat "/opt/stacks/$run-shop-staging/.env") +site "$run-shop" staging 'hostname: legacy.example.com' 'env:' ' GREETING: shop staging' +deploy_on "$run-shop" staging +[ "$status" != 0 ] || fail "a changed fragment: exit code 0" +[[ $line == "$run-shop-staging: failed: "*"the proxy refused to reload with the route of legacy.example.com, which is as it was: caddy validate says "*legacy.example.com* ]] || + fail "a changed fragment: last line: $line" +[ "$(on cat "/etc/caddy/stacks/$run-shop-staging.caddy")" = "$fragment_before" ] || fail "a changed fragment: it was not put back" +[ "$(on cat "/opt/stacks/$run-shop-staging/.env")" = "$env_before" ] || fail "a changed fragment: .env changed" +[ "$(get staging.shop.example.com /)" = 'shop staging 200' ] || fail "a changed fragment: the route: $(get staging.shop.example.com /)" +site "$run-shop" staging 'hostname: staging.shop.example.com' 'env:' ' GREETING: shop staging' +echo "✓ $case" + case='a route the proxy refuses' +# A fragment that does not parse, written by hand; Caddy names the file where +# the parse fails, which can be the one after it. printf 'broken.example.com {\n' | docker exec -i -u plexus "$host" sh -c "cat >/etc/caddy/stacks/$run-broken.caddy" site "$run-docs" preview 'hostname: preview.docs.example.com' 'env:' ' GREETING: docs preview' deploy_on "$run-docs" preview [ "$status" != 0 ] || fail "exit code 0" -[[ $line == "$run-docs-preview: failed: "*"the proxy refused the route of preview.docs.example.com"* ]] || fail "last line: $line" +[[ $line == "$run-docs-preview: failed: "*"the proxy refused to reload with the route of preview.docs.example.com, which is as it was: caddy validate says adapting config"* ]] || + fail "last line: $line" on test ! -e "/etc/caddy/stacks/$run-docs-preview.caddy" || fail "the refused fragment is still there" as_deploy rm "/etc/caddy/stacks/$run-broken.caddy" as_deploy sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload once the broken fragment is gone" From 59731ef1ade8fd9bb9a18642d12b1d39e8c9d5b2 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:47:29 +0100 Subject: [PATCH 78/91] The route script skips a port something listens on, and says why the proxy refused A new port skips every port in state LISTEN that /proc/net/tcp and /proc/net/tcp6 list, which every Linux host has, so that a first deploy does not claim a port it cannot bind and keep it for good. Where the proxy refuses the reload, the line gives the error of caddy validate, which the deploy user can run, instead of a cause the script does not know; where that says nothing, only that the proxy refused. A host without flock is told so. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/roles/stack/files/route.sh | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/ansible/platform/roles/stack/files/route.sh b/ansible/platform/roles/stack/files/route.sh index f3b15463..574b1db8 100755 --- a/ansible/platform/roles/stack/files/route.sh +++ b/ansible/platform/roles/stack/files/route.sh @@ -6,10 +6,14 @@ # serves it; # 2. takes the environment's loopback port from its .env, and where that # names none, the lowest port of the range that neither another -# directory's .env nor another environment's fragment names; +# directory's .env nor another environment's fragment names, and that +# nothing on the host listens on (TCP, IPv4 and IPv6, as /proc/net/tcp +# and /proc/net/tcp6 list it, which every Linux host has); # 3. writes the fragment /.caddy where its text changes, # and reloads the proxy through the deploy user's one sudo rule; where the -# proxy refuses the reload, it puts back what was there. +# proxy refuses the reload, it puts back what was there, and says what +# `caddy validate` says of the configuration with the new fragment, which +# the deploy user can run (the ingress role's header). # It prints `port= route=changed|unchanged`, or why it refuses, and then # exits 1. With `check` last it takes no lock, writes and reloads nothing, and # prints what it would do. The fragment's shape and the reload rule are the @@ -21,6 +25,7 @@ root=$1 fragments=$2 project=$3 hostname=$4 first=${5%-*} last=${5#*-} check=${6 fragment=$fragments/$project.caddy if [ "$check" != check ]; then + command -v flock >/dev/null || { echo "flock, of util-linux, is not on this host; the deploy takes its lock with it"; exit 1; } exec 9>>"$root/.lock" flock -w 300 9 || { echo "$root/.lock is held by another deploy and was not released within 300 seconds"; exit 1; } fi @@ -49,6 +54,10 @@ if [ -z "$port" ]; then [ -f "$other" ] && [ "$other" != "$fragment" ] && taken="$taken$(sed -n 's/^[[:space:]]*import stack \([0-9][0-9]*\).*/\1/p' "$other" | tr '\n' ' ')" done + # The local port, in hex, of each socket in state 0A, LISTEN. + for hex in $(cat /proc/net/tcp /proc/net/tcp6 2>/dev/null | sed -n 's/^ *[0-9]*: [0-9A-Fa-f]*:\([0-9A-Fa-f]*\) [0-9A-Fa-f]*:[0-9A-Fa-f]* 0A .*/\1/p'); do + taken="$taken$((0x$hex)) " + done port=$first while case "$taken" in *" $port "*) true ;; *) false ;; esac; do port=$((port + 1)); done [ "$port" -le "$last" ] || { echo "no port from $first to $last is free on this host for $project"; exit 1; } @@ -62,9 +71,12 @@ fi if [ "$check" != check ]; then previous=$(cat "$fragment" 2>/dev/null) && had=1 || had=0 printf '%s\n' "$text" >"$fragment.new" && mv "$fragment.new" "$fragment" - if ! said=$(sudo -n /usr/bin/systemctl reload caddy 2>&1); then + if ! sudo -n /usr/bin/systemctl reload caddy >/dev/null 2>&1; then + # Its error, as a line `Error: …` or a log line of level error. + why=$(caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile 2>&1 | + sed -n -e 's/^Error: //p' -e 's/.*"level":"error".*"msg":"\([^"]*\)".*/\1/p' | tail -1) if [ "$had" = 1 ]; then printf '%s\n' "$previous" >"$fragment.new" && mv "$fragment.new" "$fragment"; else rm -f "$fragment"; fi - echo "the proxy refused the route of $hostname, which is as it was; caddy validate on the host says why: $(printf '%s' "$said" | head -1)" + echo "the proxy refused to reload with the route of $hostname, which is as it was${why:+: caddy validate says $why}" exit 1 fi fi From 917c85a7a9e63aabd97802c07e09ab1051990372 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:47:46 +0100 Subject: [PATCH 79/91] The deploy root is written once, and the stack playbook's header says what its caller must know deploy_user_root, in the role deploy_user's vars, which no inventory overrides, is the one place /opt/stacks is written: the role's task uses it, and the stack playbook reads the file for stack_root's default, which -e still overrides. The header says that the caller passes no -i, --limit, --tags or --skip-tags, and which runs of no task Ansible ends with exit 0 and no Result line; that PLEXUS_TAG and PLEXUS_COMMIT_SHA are rendered into the compose file by the caller; that .env.secret ends empty once the environment has no secrets, and .env.secret.prev keeps the previous ones; and step 3 points at the route script's header instead of repeating it. Co-Authored-By: Claude Opus 5.5 --- ansible/platform/playbooks/stack.yml | 68 +++++++++++-------- .../roles/deploy_user/defaults/main.yml | 3 +- .../platform/roles/deploy_user/tasks/main.yml | 2 +- .../platform/roles/deploy_user/vars/main.yml | 6 ++ .../platform/roles/stack/defaults/main.yml | 6 +- 5 files changed, 50 insertions(+), 35 deletions(-) create mode 100644 ansible/platform/roles/deploy_user/vars/main.yml diff --git a/ansible/platform/playbooks/stack.yml b/ansible/platform/playbooks/stack.yml index 4b5d7161..fb4591e8 100644 --- a/ansible/platform/playbooks/stack.yml +++ b/ansible/platform/playbooks/stack.yml @@ -11,12 +11,23 @@ # Variables, documented in the role's defaults: stack_name, # stack_environment_file and stack_compose_file, given on every run; the # environment is named after its file (staging.yaml is staging). Further -# stack_root (/opt/stacks), stack_port_range (20000-20999) and -# stack_wait_timeout (60 seconds). It takes no inventory: the one host is the -# file's `host`, [user@]address[:port], reached as the user it names, else as -# plexus_deploy_user (the role deploy_user's default, plexus), on the port it -# names, else 22. Arguments of ansible-playbook for the connection, such as -# --ssh-common-args or --private-key, apply to it. +# stack_root (the deploy root, /opt/stacks), stack_port_range (20000-20999), +# stack_secret_timeout (30 seconds) and stack_wait_timeout (60 seconds). +# +# What the caller passes, and what not. No inventory (-i) and no --limit: the +# one host is the file's `host`, [user@]address[:port], reached as the user it +# names, else as plexus_deploy_user (the role deploy_user's default, plexus, +# whatever an inventory says), on the port it names, else 22; an inventory +# only lends the connection variables of a host of the same name. No --tags +# or --skip-tags. It refuses a --limit, --tags or --skip-tags it sees, but a +# --limit that leaves out localhost, or --skip-tags always, makes +# ansible-playbook run none of its tasks and exit 0 without a Result line. +# Arguments for the connection, such as --ssh-common-args or --private-key, +# apply. PLEXUS_TAG and PLEXUS_COMMIT_SHA are the caller's: it renders them +# into the compose file it hands over, each app's image pinned by its digest in +# place of ${PLEXUS_TAG} and the commit in place of ${PLEXUS_COMMIT_SHA}; the +# playbook writes neither, and the compose file is otherwise handed over +# uninterpolated, since the host interpolates it from .env. # # What it expects where it runs: the vault's CLI, op, with a session or a # token, where the environment has secrets. On the host, as the platform @@ -28,32 +39,28 @@ # Python. It uses no privilege escalation but that rule. # # In order, where it runs: -# 1. Checks its variables, and reads the environment's file and checks that -# it can write it: a map of `host`, `hostname`, a DNS name, `env`, names -# to strings, and `secrets`, names to op:// pointers; plx doctor checks -# the file whole. +# 1. Checks its arguments and variables, and reads the environment's file and +# checks that it can write it: a map of `host`, `hostname`, a DNS name, +# `env`, names to strings, and `secrets`, names to op:// pointers; plx +# doctor checks the file whole. # 2. Reads each pointer under `secrets` with `op read`, also in a dry run, -# and adds the host the file names. +# refusing a value that is empty in the vault, and adds the host the file +# names. # On the host, into /opt/stacks/-, the compose project of # that name: -# 3. Where the environment has a hostname, under the lock /opt/stacks/.lock, -# which a second run waits for (up to 300 seconds): refuses the hostname -# where another environment's route fragment serves it; takes the -# environment's loopback port, the one its .env holds, else the lowest of -# stack_port_range that neither another directory's .env nor another -# fragment names, so that it is kept for good; writes the fragment -# -.caddy where its text changes, and reloads the -# proxy then. Where the proxy refuses the reload, it puts the fragment -# back as it was and fails. (The role's files/route.sh.) +# 3. Where the environment has a hostname, claims its loopback port and +# writes its route (the role's files/route.sh says how). # 4. Creates the directory where it is missing, mode 0750. # 5. Renders .env from `env`, with COMPOSE_PROJECT_NAME and, where the # environment has a hostname, PLEXUS_LOOPBACK_PORT; .env.secret, mode # 0600, from the secrets' values, where the environment has secrets or -# the directory holds one already; each value double-quoted and escaped -# (templates/dotenv.j2), so that Compose reads it back as written. -# Compares them, and the compose file, with the files in place: a file -# that changes is kept as .prev, all of them before the first is -# written, and then written, .env, .env.secret, compose.yaml. +# the directory holds one already, which ends empty once the environment +# has none; each value double-quoted and escaped (templates/dotenv.j2), so +# that Compose reads it back as written. Compares them, and the compose +# file, with the files in place: a file that changes is kept as +# .prev, all of them before the first is written, and then written, +# .env, .env.secret, compose.yaml. .env.secret.prev, 0600, keeps the +# previous secrets until .env.secret changes again. # 6. Pulls the images, where compose.yaml changed, so that an image that # cannot be had fails the deploy before migrate runs, and a tag that moved # since the last deploy is fetched, which run and up, pulling only what is @@ -89,12 +96,15 @@ # Nothing locks an environment as a whole: two runs for the same environment # at the same time are not supported, and can both fail, one undoing what the # other made. What keeps them apart is the pipeline's own order, one deploy job -# per branch at a time. The lock of 3 keeps two environments from one port. +# per branch at a time. # # No secret's value appears in the run's output, with -v or --diff either: # every task that holds one prints nothing of it. # -# The last task, Result, prints one line as its `msg`: +# The last task, Result, prints one line as its `msg`. Every run prints it, and +# exits 0 only where it says deployed, unchanged or would deploy, but for the +# two runs of no task above and a host that cannot be reached, which Ansible's +# own error ends, with exit code 4: # -: deployed a file or the route changed, or a container was # started or taken down; healthy # -: unchanged nothing changed, and healthy @@ -104,8 +114,7 @@ # names the step that failed and the first line of its error, as in # `'Bring the stack up and wait for health' failed (rc 1): General error: # container shop-staging-web-1 is unhealthy`. Where the check of the -# variables fails, the line begins `the stack:`. The task, and with it the -# run, fails unless the line says deployed, unchanged or would deploy. +# arguments or the variables fails, the line begins `the stack:`. # # --check, with --diff, runs 1 to 5 and shows whether .env, .env.secret, # compose.yaml and the route would change, and how, but for .env.secret. It @@ -129,6 +138,7 @@ hosts: stack_host gather_facts: false vars_files: + - ../roles/deploy_user/vars/main.yml # deploy_user_root - ../roles/ingress/defaults/main.yml # ingress_fragments_dir roles: - { role: plexus.platform.stack, tags: [always] } diff --git a/ansible/platform/roles/deploy_user/defaults/main.yml b/ansible/platform/roles/deploy_user/defaults/main.yml index 7d9c4730..5c634cd8 100644 --- a/ansible/platform/roles/deploy_user/defaults/main.yml +++ b/ansible/platform/roles/deploy_user/defaults/main.yml @@ -1,8 +1,7 @@ --- # The unprivileged user that owns the deploy root and as which the stack # playbook deploys over SSH; the role creates both, and changes nothing below -# the root. The deploy root is /opt/stacks and no variable: it is the path the -# stack contract names for every environment (PLX-Stack/HostDirectory). +# the root. The deploy root is no setting: vars/main.yml names it. # # The plexus_ variables are shared with other roles (plexus.host.docker adds # the user to the docker group), so they keep that prefix; set them in the diff --git a/ansible/platform/roles/deploy_user/tasks/main.yml b/ansible/platform/roles/deploy_user/tasks/main.yml index 7b0af778..ca7e2600 100644 --- a/ansible/platform/roles/deploy_user/tasks/main.yml +++ b/ansible/platform/roles/deploy_user/tasks/main.yml @@ -10,7 +10,7 @@ # Not recursive: what lies below is the stack playbook's. - name: Give the deploy user the deploy root ansible.builtin.file: - path: /opt/stacks + path: "{{ deploy_user_root }}" state: directory owner: "{{ plexus_deploy_user }}" group: "{{ plexus_deploy_user }}" diff --git a/ansible/platform/roles/deploy_user/vars/main.yml b/ansible/platform/roles/deploy_user/vars/main.yml new file mode 100644 index 00000000..78f23649 --- /dev/null +++ b/ansible/platform/roles/deploy_user/vars/main.yml @@ -0,0 +1,6 @@ +--- +# The deploy root, the one place it is written: the path the stack contract +# names for every environment (PLX-Stack/HostDirectory), so no setting, and in +# the role's vars, which no inventory overrides. The stack playbook reads this +# file for its stack_root. +deploy_user_root: /opt/stacks diff --git a/ansible/platform/roles/stack/defaults/main.yml b/ansible/platform/roles/stack/defaults/main.yml index af79400c..6ecd63ba 100644 --- a/ansible/platform/roles/stack/defaults/main.yml +++ b/ansible/platform/roles/stack/defaults/main.yml @@ -10,9 +10,9 @@ # stack_compose_file the stack's rendered compose file on that machine, # every app's image pinned by digest -# Where the environments live on the host, each in /- -# (PLX-Stack/HostDirectory; the role deploy_user gives the deploy user the same path). -stack_root: /opt/stacks +# Where the environments live on the host, each in /-: +# the deploy root, which the playbook reads from the role deploy_user's vars. +stack_root: "{{ deploy_user_root }}" # The ports an environment's loopback port is taken from, -: the # lowest that no other environment on the host holds, taken once and kept. From 0a925d912419fb0f5c72c1b992f09f4996357485 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:04:43 +0100 Subject: [PATCH 80/91] plx deploy's test: the variables go as one JSON object, from a checkout whose path has a space and an = Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/deploy.test.ts | 64 ++++++++++++++++++++---- 1 file changed, 53 insertions(+), 11 deletions(-) diff --git a/packages/cli/src/commands/deploy.test.ts b/packages/cli/src/commands/deploy.test.ts index 29c05552..fb2034e7 100644 --- a/packages/cli/src/commands/deploy.test.ts +++ b/packages/cli/src/commands/deploy.test.ts @@ -73,16 +73,32 @@ exit 1 */ const ANSIBLE = `printf '%s\\n' "$*" >> "$FAKE/ansible.log" check= syntax= name= envfile= file= last= +# An extra variable as Ansible reads it: a JSON object, else key=value words split on whitespace, which a word with no +# \`=\` is no variable of. +extra() { + node -e 'const v = process.argv[1]; let o = {}; + if (v.startsWith("{")) o = JSON.parse(v); + else for (const w of v.split(/\\s+/).filter(Boolean)) { + const i = w.indexOf("="); + if (i < 0) { console.error("ERROR: Invalid extra vars: " + w); process.exit(1); } + o[w.slice(0, i)] = w.slice(i + 1); + } + console.log([o.stack_name ?? "", o.stack_environment_file ?? "", o.stack_compose_file ?? ""].join("\\n"));' "$1" +} for a in "$@"; do case "$a" in --syntax-check) syntax=1 ;; --check) check=1 ;; esac - case "$last$a" in - -estack_name=*) name=\${a#stack_name=} ;; - -estack_environment_file=*) envfile=\${a#stack_environment_file=} ;; - -estack_compose_file=*) file=\${a#stack_compose_file=} ;; - esac + if [ "$last" = -e ]; then + got=$(extra "$a") || exit 1 + { read -r n; read -r e; read -r c; } < = { /** `plx deploy` for staging in the fixture's checkout, with more arguments. */ const staging = (f: Fixture, ...more: string[]) => ['deploy', '-e', 'staging', '--commit', SHA, '-C', f.repo, ...more]; +/** The one JSON object of variables a call of the playbook was given, as the text it was written in. */ +const varsIn = (call: string): string => /-e (\{.*\})/.exec(call)?.[1] ?? ''; +/** The variables of a call. */ +const varsOf = (call: string): Record => JSON.parse(varsIn(call) || '{}'); + /** The calls of the stack playbook that deployed, one line each, without the check that it is installed. */ const runs = (fake: string): string[] => existsSync(join(fake, 'ansible.log')) @@ -279,17 +300,38 @@ test('plx deploy renders each stack with every app image pinned by the digest it ]); }); +test('the variables go to the playbook as one JSON object, so a checkout whose path has a space and an = deploys', async () => { + const f = fixture('sp ace=x-'); + assert.match(f.repo, /sp ace=x-/); + const err = await plx(staging(f), f.fake); + assert.deepEqual(summary(err), ['✓ admin-staging: deployed', '✓ docs-staging: deployed', '✓ shop-staging: deployed']); + const calls = runs(f.fake); + assert.equal(calls.length, 3); + for (const call of calls) { + assert.equal(call.match(/ -e /g)?.length, 1, 'one -e: a variable of the call is no word of its own'); + assert.equal(varsOf(call).stack_environment_file?.startsWith(f.repo), true, call); + } +}); + test('plx deploy runs the stack playbook once per stack with the environment file of the stack, all stacks at once, and ends with one line per stack', async () => { const f = fixture(); writeFileSync(join(f.fake, 'together'), 'shop\nadmin\ndocs\n'); const err = await plx(staging(f), f.fake); const calls = runs(f.fake); assert.equal(calls.length, 3, calls.join('\n')); - const call = (name: string) => calls.find((c) => c.includes(`stack_name=${name} `)) ?? ''; + const call = (name: string) => calls.find((c) => varsOf(c).stack_name === name) ?? ''; // The host, its user and its port are the file's, which the playbook reads: no inventory, no user, no environment name. assert.equal( - call('shop').replace(/stack_compose_file=\S+/, 'stack_compose_file='), - `--ssh-common-args -o StrictHostKeyChecking=accept-new -e stack_name=shop -e stack_environment_file=${join(f.repo, 'stacks/shop/staging.yaml')} -e stack_compose_file= plexus.platform.stack`, + call('shop').replace(varsIn(call('shop')), ''), + '--ssh-common-args -o StrictHostKeyChecking=accept-new -e plexus.platform.stack', + ); + assert.deepEqual( + { ...varsOf(call('shop')), stack_compose_file: '' }, + { + stack_name: 'shop', + stack_environment_file: join(f.repo, 'stacks/shop/staging.yaml'), + stack_compose_file: '', + }, ); for (const call of calls) assert.doesNotMatch(call, /(^| )-[iu] |stack_environment=|ansible_port/); assert.doesNotMatch(err, /ran alone/, 'every stack ran while the others did'); @@ -686,7 +728,7 @@ test('without the collection where Ansible looks the run is refused, saying how // --- the dry run and the arguments for ansible-playbook ------------------------------------------- /** The compose file a call of the playbook was handed. */ -const handed = (call: string) => /-e stack_compose_file=(\S+)/.exec(call)?.[1] ?? ''; +const handed = (call: string) => varsOf(call).stack_compose_file ?? ''; test('a dry run is the playbook’s own, --check --diff, after every read; it keeps the files it handed over and names where', async () => { const f = fixture(); From 5ae3a695ed7c41ad86ef6308721be7d8c9f2a812 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:07:08 +0100 Subject: [PATCH 81/91] plx deploy passes the playbook's variables as one JSON object, words the loader's refusal as it wrote it and names the missing vault secret in CI Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/deploy.test.ts | 38 ++++++++++++++++++++++++ packages/lib/src/deploy.ts | 38 +++++++++++++++++------- packages/lib/src/deployTargets.ts | 11 +++---- packages/lib/src/index.ts | 2 +- 4 files changed, 71 insertions(+), 18 deletions(-) diff --git a/packages/cli/src/commands/deploy.test.ts b/packages/cli/src/commands/deploy.test.ts index fb2034e7..d50fc65c 100644 --- a/packages/cli/src/commands/deploy.test.ts +++ b/packages/cli/src/commands/deploy.test.ts @@ -552,6 +552,44 @@ test('an environment file with a problem refuses the run before any host is reac assert.equal(existsSync(join(f.fake, 'docker.log')), false, 'no registry was read'); }); +test('a refusal gives the loader’s message as it wrote it: an op:// pointer stays op://', async () => { + const f = fixture(); + put(f.repo, environment('admin', 'staging', 'a.example.com', 'secrets: {TOKEN: not-a-pointer}\n')); + await assert.rejects( + plx(staging(f), f.fake), + (e: unknown) => + e instanceof UsageError && + e.message.includes('stacks/admin/staging.yaml') && + e.message.includes('is no `op://` pointer') && + !e.message.includes('op:/`'), + ); +}); + +test('in CI an environment with secrets and no vault token is refused by naming the repository secret, before any host or registry is touched; a person at a checkout is not', async () => { + const withSecrets = (f: Fixture) => + put(f.repo, environment('admin', 'staging', 'a.example.com', 'secrets: {TOKEN: op://acme/admin/token}\n')); + const ci = { GITHUB_ACTIONS: 'true', OP_SERVICE_ACCOUNT_TOKEN: '' }; + const f = fixture(); + withSecrets(f); + await assert.rejects( + plx(staging(f), f.fake, ci), + (e: unknown) => + e instanceof UsageError && + e.message.includes('DEPLOY_VAULT_TOKEN') && + e.message.includes('stacks/admin/staging.yaml'), + ); + assert.equal(existsSync(join(f.fake, 'ansible.log')), false, 'no playbook ran'); + assert.equal(existsSync(join(f.fake, 'docker.log')), false, 'no registry was read'); + // A token, a person's session (no CI), or no secrets at all: the run goes on. + await plx(staging(f), f.fake, { ...ci, OP_SERVICE_ACCOUNT_TOKEN: 'a-token' }); + const person = fixture(); + withSecrets(person); + await plx(staging(person), person.fake, { GITHUB_ACTIONS: '', OP_SERVICE_ACCOUNT_TOKEN: '' }); + const bare = fixture(); + await plx(staging(bare), bare.fake, ci); + assert.equal(runs(bare.fake).length, 3); +}); + test('in the human mode plx deploy prints no result on stdout, and with --json the result', async () => { const f = fixture(); await plx(staging(f), f.fake); diff --git a/packages/lib/src/deploy.ts b/packages/lib/src/deploy.ts index 4db8e42f..b2a3e028 100644 --- a/packages/lib/src/deploy.ts +++ b/packages/lib/src/deploy.ts @@ -51,10 +51,12 @@ // version of the collection is installed is not checked. // 5. The runs, one per stack with the file, all at once: // ansible-playbook --ssh-common-args '-o StrictHostKeyChecking=accept-new' -// -e stack_name= -e stack_environment_file= -// -e stack_compose_file= [--check --diff] +// -e '{"stack_name": , "stack_environment_file": , +// "stack_compose_file": }' [--check --diff] // [] plexus.platform.stack -// with no inventory, user or port: the playbook takes the host from the +// with no inventory, user or port, and the variables as one JSON object, +// since Ansible splits `key=value` words on whitespace and a path may +// hold some: the playbook takes the host from the // file, and the environment's name from its name; it resolves the file's // `op://` pointers where it runs, with the `op` there (§ 1 PLX-Secrets). // The run is in the run's directory, so that no ansible.cfg of the @@ -79,11 +81,12 @@ // registry an app's image is in (for the digests); ansible-playbook on the // PATH and the collection plexus.platform where Ansible looks, which brings // community.docker at the version its galaxy.yml names (for any stack with a -// file); SSH access to each file's host as the user it names, whose host key +// file); SSH access to each file's host as the user it names, else the default user the stack playbook's header names, whose host key // is taken on first contact (accept-new) into the known_hosts of whoever runs // it; and, where an environment has secrets, `op` on the PATH, signed in or // with OP_SERVICE_ACCOUNT_TOKEN, which the playbook reads them with. A person // runs the same verb from a checkout with their own session of the vault. +// In CI (GITHUB_ACTIONS), a run whose files list secrets and that has no OP_SERVICE_ACCOUNT_TOKEN is refused before any host is reached, naming the repository secret DEPLOY_VAULT_TOKEN. // // Every process the verb starts runs in a process group of its own, with a // limit: two minutes for a read (a digest, the syntax check), an hour for a @@ -211,6 +214,7 @@ export async function deploy(ctx: Context, options: DeployOptions): Promise ({ stack: s, file: s.environments.find((e) => e.name === environment) })); refuseFiles(repo.root, named, environment); + refuseMissingToken(repo.root, named); const legs = named.flatMap(({ stack, file }): Leg[] => file ? [{ stack: stack.name, file: file.file, host: file.host as string }] : [], ); @@ -334,12 +338,29 @@ function refuseFiles( environment: string, ): void { const lines = named.flatMap(({ stack, file }) => - (file?.problems ?? []).map((problem) => join(relative(root, stack.dir), problem)), + (file?.problems ?? []).map((problem) => `${relative(root, stack.dir)}/${problem}`), ); if (lines.length > 0) throw new UsageError(`${lines.join('\n')}\nno stack was deployed into ${environment}; plx doctor reports the same`); } +/** + * In CI, where the playbook resolves pointers with the repository's secret + * `DEPLOY_VAULT_TOKEN` as OP_SERVICE_ACCOUNT_TOKEN, a run with pointers and + * no token is refused here, naming the secret, since op's own error does not. + * A person at a checkout has a session of their own, and is not asked. + */ +function refuseMissingToken(root: string, named: { stack: Stack; file: Environment | undefined }[]): void { + if (process.env.GITHUB_ACTIONS !== 'true' || process.env.OP_SERVICE_ACCOUNT_TOKEN) return; + const files = named.flatMap(({ stack, file }) => + file && Object.keys(file.secrets).length > 0 ? [`${relative(root, stack.dir)}/${file.name}.yaml`] : [], + ); + if (files.length > 0) + throw new UsageError( + `${files.join(', ')} list secrets, and the job has no token to read them with: the repository secret DEPLOY_VAULT_TOKEN is missing or empty; no host was reached`, + ); +} + /** The loader's problems, but an app no stack uses, as one refusal. */ function refuseProblems(problems: StackProblem[]): void { const blocking = problems.filter((p) => p.code !== 'unused-app'); @@ -520,12 +541,9 @@ async function runStack( const args = [ '--ssh-common-args', '-o StrictHostKeyChecking=accept-new', + // One JSON object: Ansible splits `key=value` words on whitespace, which a path of a checkout may hold. '-e', - `stack_name=${stack}`, - '-e', - `stack_environment_file=${leg.file}`, - '-e', - `stack_compose_file=${file}`, + JSON.stringify({ stack_name: stack, stack_environment_file: leg.file, stack_compose_file: file }), ...(ctx.dryRun ? ['--check', '--diff'] : []), ...(options.ansible ?? []), PLAYBOOK, diff --git a/packages/lib/src/deployTargets.ts b/packages/lib/src/deployTargets.ts index f41d7a9b..5551a7d3 100644 --- a/packages/lib/src/deployTargets.ts +++ b/packages/lib/src/deployTargets.ts @@ -1,9 +1,6 @@ -// the environment a branch deploys into (§ 3 PLX-Delivery): `environmentOf` -// is the one place that says it, for `plx` and `plx-ci`. Where a stack goes is -// not here: it is the `host` of the stack's environment file (environments.ts). - -/** The environment main deploys into. */ -export const DEFAULT_ENVIRONMENT = 'production'; +// The branches that deploy and the environment each deploys into (§ 3 PLX-Delivery): `environmentOf` is the +// one place that says it, for `plx` and `plx-ci`; `ENVIRONMENT_BRANCHES` is the list it applies and a refusal names. +// Where a stack goes is not here: it is the `host` of the stack's environment file (environments.ts). /** * The environment a run deploys into (§ 3 PLX-Delivery): `given` when the @@ -20,4 +17,4 @@ export function environmentOf(event: string, ref: string, given = ''): string { } /** The branches that deploy, each into its environment: the rule `environmentOf` applies, and the list a refusal names. */ -export const ENVIRONMENT_BRANCHES: Readonly> = { main: DEFAULT_ENVIRONMENT, develop: 'staging' }; +export const ENVIRONMENT_BRANCHES: Readonly> = { main: 'production', develop: 'staging' }; diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 378d343a..d2797a77 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -42,7 +42,7 @@ export { renderCommitSha, type StackOutcome, } from './deploy.ts'; -export { DEFAULT_ENVIRONMENT, ENVIRONMENT_BRANCHES, environmentOf } from './deployTargets.ts'; +export { ENVIRONMENT_BRANCHES, environmentOf } from './deployTargets.ts'; export { type AppFacts, CHECKS, From b0cf0a2320c946c284f2783a57a6584d0e0f9ed6 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:07:50 +0100 Subject: [PATCH 82/91] The doctor's test: a deviation under a removed requirement is told the requirement was removed Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.test.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 43acaeaf..645064f5 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -14,6 +14,7 @@ import { overview } from './overview.ts'; import type { MarkerSite } from './sites.ts'; import { type Bundled, strayKeys } from './siteTemplates.ts'; import { parseImage, type RepoStacks, type Stack, type StackProblem } from './stacks.ts'; +import { bundledIndex } from './standardIndex.ts'; import { templatesRoot } from './templatesRoot.ts'; import { type FakeExec, fakeIo, link, type Tree, UNREADABLE } from './testing/fakeIo.ts'; import { UsageError } from './version.ts'; @@ -2788,6 +2789,23 @@ test('a cyclic alias in compose.yaml is reported as a compose file that cannot b assert.match(found[0]?.problem ?? '', /aliases form a cycle/); }); +test('a deviation under a requirement the standard removed is told so, and the index no longer names it', () => { + // Joined at run time, as a removed name must not read as a citation of the compendium's. + const removed = [['PLX-Stack', 'PathPrefix'].join('/'), ['PLX-Ingress', 'PrefixInRecord'].join('/')]; + for (const name of removed) { + assert.equal(bundledIndex().citable.includes(name), false, `${name} is in the index`); + // Also with an index that still names it, as an earlier version's does. + for (const index of [KNOWN, new Set([...KNOWN, name])]) + assert.deepEqual(diagnose([stack('stateless', {}, [name])], index).units[0]?.findings, [ + { + requirement: name, + problem: + 'listed under `deviations`, but this requirement was removed from the standard: the deviation can go', + }, + ]); + } +}); + test('a deviation under a name released in an earlier version is told what it is now', () => { // Joined at run time, as the old name must not read as a citation of the compendium's. const old = ['PLX-Stack', 'NoCommittedValues'].join('/'); From 2795317edc8c192b9c9a7fb39b0a0592ddb36d7a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:08:15 +0100 Subject: [PATCH 83/91] A deviation under PLX-Stack/PathPrefix or PLX-Ingress/PrefixInRecord is told the requirement was removed; the index names neither Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.ts | 11 +++++++++++ packages/lib/src/standard-index.json | 2 -- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 8adf1e53..46571237 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -703,6 +703,12 @@ const MOVED_TO_STACK = new Set([ /** What a requirement that was renamed as it moved is called now. */ const RENAMED_ON_MOVE: Readonly> = { NoCommittedValues: 'NoCommittedSecrets' }; +/** + * Requirements the standard removed: a deviation under one of them can go, whatever an index of an earlier version + * says. Joined at run time, as a removed name is no citation of the compendium's. + */ +const REMOVED = new Set([['PLX-Stack', 'PathPrefix'].join('/'), ['PLX-Ingress', 'PrefixInRecord'].join('/')]); + /** What a released `PLX-Stack/…` name is called now, where it was renamed; the `PLX-App/…` form is `movedTo`'s. */ function renamedInStack(name: string): string | undefined { const rest = name.startsWith('PLX-Stack/') ? name.slice('PLX-Stack/'.length) : undefined; @@ -798,6 +804,11 @@ function diagnoseUnit(unit: Facts, known: Set): UnitReport { requirement: name, problem: `listed under \`deviations\`, but no requirement has this name: it is now \`${renamedInStack(name)}\``, }); + else if (REMOVED.has(name)) + findings.push({ + requirement: name, + problem: 'listed under `deviations`, but this requirement was removed from the standard: the deviation can go', + }); else if (!known.has(name)) findings.push({ requirement: name, problem: 'listed under `deviations`, but no requirement has this name' }); else if (!reasonGiven(declaration?.body ?? '', name)) diff --git a/packages/lib/src/standard-index.json b/packages/lib/src/standard-index.json index 541513ff..428bc4b4 100644 --- a/packages/lib/src/standard-index.json +++ b/packages/lib/src/standard-index.json @@ -152,7 +152,6 @@ "PLX-Stack/ReservedPrefix", "PLX-Stack/SinglePort", "PLX-Stack/LoopbackPort", - "PLX-Stack/PathPrefix", "PLX-Stack/Healthcheck", "PLX-Stack/HostDirectory", "PLX-Stack/ComposeDelivery", @@ -219,7 +218,6 @@ "§ 3 PLX-Infrastructure", "§ 1 PLX-Ingress", "§ 2 PLX-Ingress", - "PLX-Ingress/PrefixInRecord", "PLX-Ingress/OneStackPerPrefix", "§ 1 PLX-JS", "§ 2 PLX-JS", From 674c326be105769cd4019167264a113939db6758 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:09:18 +0100 Subject: [PATCH 84/91] merge's test: a birth-only path is written at a birth and never by an update Co-Authored-By: Claude Sonnet 5.5 --- packages/cli-template/src/merge.test.ts | 37 +++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/packages/cli-template/src/merge.test.ts b/packages/cli-template/src/merge.test.ts index e593ca48..600bddab 100644 --- a/packages/cli-template/src/merge.test.ts +++ b/packages/cli-template/src/merge.test.ts @@ -15,6 +15,8 @@ interface Case { readonly current?: Listing; /** The paths whose policy is born-once: in both renders, or in each. */ readonly bornOnce?: readonly string[] | { readonly old: readonly string[]; readonly new: readonly string[] }; + /** The paths whose policy is birth-only, in the new render. */ + readonly birthOnly?: readonly string[]; /** What the fake merge of one file reports. */ readonly conflicted?: boolean; } @@ -38,8 +40,14 @@ async function run(c: Case) { }; const bornOnce = c.bornOnce ?? []; const { old: bornOld, new: bornNew } = 'old' in bornOnce ? bornOnce : { old: bornOnce, new: bornOnce }; - const policies = (l: Listing, born: readonly string[]): Policies => - new Map(Object.keys(l).map((path) => [path, { policy: born.includes(path) ? 'born-once' : 'merge' }])); + const birthOnly = c.birthOnly ?? []; + const policies = (l: Listing, born: readonly string[], only: readonly string[] = []): Policies => + new Map( + Object.keys(l).map((path) => [ + path, + { policy: only.includes(path) ? 'birth-only' : born.includes(path) ? 'born-once' : 'merge' }, + ]), + ); const old = c.old ?? {}; const next = c.new ?? {}; const result = await merge( @@ -47,7 +55,7 @@ async function run(c: Case) { old: tree(old), new: tree(next), current: tree(c.current ?? {}), - files: { old: policies(old, bornOld), new: policies(next, bornNew) }, + files: { old: policies(old, bornOld, birthOnly), new: policies(next, bornNew, birthOnly) }, }, mergeFile, ); @@ -283,6 +291,29 @@ test('merge leaves absent a path the user deleted, even where the template chang }); }); +test('merge writes a birth-only path where the old render holds nothing, a birth, and never where the old render holds anything: an update adds none, and touches none the current tree has', async () => { + const born = await run({ new: { 'compose.txt': 'c\n', 'env.txt': 'e\n' }, birthOnly: ['env.txt'] }); + assert.deepEqual(born, { + tree: { 'compose.txt': 'c\n', 'env.txt': 'e\n' }, + report: ['compose.txt: added', 'env.txt: added'], + calls: [], + }); + const updated = await run({ + old: { 'compose.txt': 'c\n' }, + new: { 'compose.txt': 'c\n', 'env.txt': 'e\n' }, + current: { 'compose.txt': 'mine\n' }, + birthOnly: ['env.txt'], + }); + assert.deepEqual(updated, { tree: { 'compose.txt': 'mine\n' }, report: [], calls: [] }); + const had = await run({ + old: { 'compose.txt': 'c\n' }, + new: { 'compose.txt': 'c\n', 'env.txt': 'e\n' }, + current: { 'compose.txt': 'c\n', 'env.txt': 'mine\n' }, + birthOnly: ['env.txt'], + }); + assert.deepEqual(had, { tree: { 'compose.txt': 'c\n', 'env.txt': 'mine\n' }, report: [], calls: [] }); +}); + // Ported from tests/test_updatediff.py, test_skip_update_deleted, where our // rule differs: copier writes a skipped file the user deleted again on an // update; merge leaves it absent, like any file the user deleted, since the old From 4b51e1976539972722533b6e09a451b2c63b272c Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:10:08 +0100 Subject: [PATCH 85/91] The engine's policy birth-only: a path written at a birth and never added by an update Co-Authored-By: Claude Sonnet 5.5 --- packages/cli-template/src/directories.test.ts | 2 +- packages/cli-template/src/directory.ts | 4 ++-- packages/cli-template/src/manifest.ts | 4 ++-- packages/cli-template/src/merge.test.ts | 2 +- packages/cli-template/src/merge.ts | 8 ++++++-- packages/cli-template/src/types.ts | 6 ++++-- 6 files changed, 16 insertions(+), 10 deletions(-) diff --git a/packages/cli-template/src/directories.test.ts b/packages/cli-template/src/directories.test.ts index 8792a404..81d8614b 100644 --- a/packages/cli-template/src/directories.test.ts +++ b/packages/cli-template/src/directories.test.ts @@ -107,7 +107,7 @@ test('planMerge rejects a target that is not a directory', async () => { }); /** A side from literal files, every one under one policy. */ -function literal(files: Record, policy: 'merge' | 'born-once' = 'merge') { +function literal(files: Record, policy: 'merge' | 'born-once' | 'birth-only' = 'merge') { return { tree: new Map(Object.entries(files).map(([path, text]) => [path, { bytes: Buffer.from(text), mode: 0o100644 }])), policies: new Map(Object.keys(files).map((path) => [path, { policy }])), diff --git a/packages/cli-template/src/directory.ts b/packages/cli-template/src/directory.ts index f38889d4..a3a84282 100644 --- a/packages/cli-template/src/directory.ts +++ b/packages/cli-template/src/directory.ts @@ -294,7 +294,7 @@ export const policiesOf = (dir: string): string => `${resolve(dir)}.plx-template /** The version of the policies file `render` writes and `readRender` reads. */ export const POLICIES_VERSION = 1; -const POLICIES: readonly string[] = ['merge', 'born-once'] satisfies Policy[]; +const POLICIES: readonly string[] = ['merge', 'born-once', 'birth-only'] satisfies Policy[]; /** Whether `value` is a JSON object: not null, not a list. */ export function isObject(value: unknown): value is Record { @@ -337,7 +337,7 @@ async function readPolicies(dir: string, tree: Tree): Promise { if (!isObject(parsed.files)) return fail('has no files: a map of path to { template, policy }'); const files = Object.entries(parsed.files); const bad = files.filter(([, v]) => !isObject(v) || !POLICIES.includes(v.policy as string)).map(([path]) => path); - if (bad.length > 0) return fail(`gives no policy, merge or born-once, to ${bad.join(', ')}`); + if (bad.length > 0) return fail(`gives no policy, merge, born-once or birth-only, to ${bad.join(', ')}`); const lacking = [...tree.keys()].filter((path) => !(path in (parsed.files as object))); if (lacking.length > 0) return fail(`lacks ${lacking.join(', ')}, which its render holds`); const extra = files.map(([path]) => path).filter((path) => !tree.has(path)); diff --git a/packages/cli-template/src/manifest.ts b/packages/cli-template/src/manifest.ts index 70c0c025..025461e6 100644 --- a/packages/cli-template/src/manifest.ts +++ b/packages/cli-template/src/manifest.ts @@ -31,7 +31,7 @@ // colour: # required: an error when nothing supplies it // size: {default: small} # optional: the default when nothing supplies it // policies: # by source path below files/, as written there -// "notes.md.jinja": born-once # merge (every path not listed) or born-once +// "notes.md.jinja": born-once # merge (every path not listed), born-once or birth-only // birth: # commands for whoever creates a directory from the // - [git, init] # template, each an argument vector; never run here // @@ -79,7 +79,7 @@ export const VARIABLES = 'variables.json'; const KEYS = ['name', 'questions', 'reads', 'policies', 'birth']; const FIELDS = ['type', 'default', 'help', 'when', 'validator', 'choices']; const TYPES: readonly string[] = ['str', 'int', 'float', 'bool', 'yaml', 'json'] satisfies QuestionType[]; -const POLICIES: readonly string[] = ['merge', 'born-once'] satisfies Policy[]; +const POLICIES: readonly string[] = ['merge', 'born-once', 'birth-only'] satisfies Policy[]; /** What a template is called: lowercase letters, digits and hyphens, from a letter. */ export const TEMPLATE_NAME = /^[a-z][a-z0-9-]*$/; const VARIABLE = /^[A-Za-z][A-Za-z0-9_]*$/; diff --git a/packages/cli-template/src/merge.test.ts b/packages/cli-template/src/merge.test.ts index 600bddab..979e7a1f 100644 --- a/packages/cli-template/src/merge.test.ts +++ b/packages/cli-template/src/merge.test.ts @@ -311,7 +311,7 @@ test('merge writes a birth-only path where the old render holds nothing, a birth current: { 'compose.txt': 'c\n', 'env.txt': 'mine\n' }, birthOnly: ['env.txt'], }); - assert.deepEqual(had, { tree: { 'compose.txt': 'c\n', 'env.txt': 'mine\n' }, report: [], calls: [] }); + assert.deepEqual(had, { tree: { 'compose.txt': 'c\n', 'env.txt': 'mine\n' }, report: ['env.txt: kept'], calls: [] }); }); // Ported from tests/test_updatediff.py, test_skip_update_deleted, where our diff --git a/packages/cli-template/src/merge.ts b/packages/cli-template/src/merge.ts index b6613c09..542f85d9 100644 --- a/packages/cli-template/src/merge.ts +++ b/packages/cli-template/src/merge.ts @@ -10,7 +10,8 @@ // // 1. the new render holds it, and neither the old render nor current does: // the path is new to the template and written, `added`, whatever its -// policy, since this is a born-once file's birth; but `kept` where a +// policy, since this is a born-once file's birth; but not at all where its +// policy is birth-only and the old render holds anything, an update; and `kept` where a // directory it lies in is a symlink in the current tree, and // `conflicted` where one is a file // 2. the old and the new render hold it alike: left alone @@ -101,7 +102,10 @@ export async function merge(input: MergeInput, mergeFile: MergeFile): Promise 0 && !old.has(path) && !tree.has(path)) continue; const outcome = await mergePath(path, old.get(path), next.get(path), bornOnce, tree, mergeFile); if (outcome !== undefined) report.push({ path, outcome }); } diff --git a/packages/cli-template/src/types.ts b/packages/cli-template/src/types.ts index 7bb77677..b85b92b1 100644 --- a/packages/cli-template/src/types.ts +++ b/packages/cli-template/src/types.ts @@ -51,7 +51,9 @@ // Each rendered path has an owner, the template that wrote it, and a policy: // `merge` (the default) or `born-once`, written only at birth, where neither // the old render nor the current directory holds the path, and never touched -// or deleted after. `merge` takes the policies of both renders, the old one's +// or deleted after; or `birth-only`, a born-once path that is written at a +// birth alone, where the old render holds nothing, so that an update never adds +// it to a directory that was born before the template had it. `merge` takes the policies of both renders, the old one's // for the paths only it has. // // `merge` takes three trees, the old render, the new render and the current @@ -97,7 +99,7 @@ export type Tree = ReadonlyMap; export type Answers = Readonly>; /** How `merge` treats a path. */ -export type Policy = 'merge' | 'born-once'; +export type Policy = 'merge' | 'born-once' | 'birth-only'; /** The six types an answer is cast to. */ export type QuestionType = 'str' | 'int' | 'float' | 'bool' | 'yaml' | 'json'; From 9a8b66f5d4a12dd4a25094b30ee016579ad288c6 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:10:38 +0100 Subject: [PATCH 86/91] The stack's tests: an update adds no environment file to a stack, a birth renders both Co-Authored-By: Claude Sonnet 5.5 --- newborns/update-released.test.ts | 30 ++++++++++++++++++++++++++++++ packages/lib/src/stack.test.ts | 5 ++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/newborns/update-released.test.ts b/newborns/update-released.test.ts index 1ac54767..2607aff7 100644 --- a/newborns/update-released.test.ts +++ b/newborns/update-released.test.ts @@ -253,6 +253,36 @@ for (const kind of ['app', 'operations'] as const) { }); } +/** A stack of the released version in `repo`, at `stacks/docs`, with its files committed and pushed; the branch the repo is on. */ +async function addStack(repo: string): Promise { + await sh('node', [plxOf(RELEASED), 'new', 'stacks/docs', 'stack', '-a', 'tenant=acme'], repo, env); + await git(repo, 'add', '-A'); + await git(repo, 'commit', '-q', '-m', 'a stack of the released version'); + await sh('git', ['push', '-q', 'origin', 'main'], repo, env); +} + +test(`operations: a stack of ${RELEASED} gets no environment file from the update, which touches none the person wrote`, async () => { + const repo = await repoAt(RELEASED, 'operations'); + await addStack(repo); + const written = 'host: deploy@own.example.com\nenv: {}\nsecrets: {}\n'; + writeFileSync(join(repo, 'stacks', 'docs', 'production.yaml'), written); + await git(repo, 'add', '-A'); + await git(repo, 'commit', '-q', '-m', 'the production file, written by a person'); + await sh('git', ['push', '-q', 'origin', 'main'], repo, env); + const taken = await take(FIRST, repo, FIRST); + assert.ok(taken.ok, taken.output); + const files = execFileSync('git', ['ls-tree', '--name-only', `plexus/${FIRST}`, 'stacks/docs/'], { + cwd: originOf(repo), + encoding: 'utf8', + }) + .trim() + .split('\n'); + // Its own file stays as written; no staging file is added, and nothing is said of one. + assert.deepEqual(files, ['stacks/docs/PLEXUS.md', 'stacks/docs/compose.yaml', 'stacks/docs/production.yaml']); + assert.equal(taken.read('stacks/docs/production.yaml'), written); + assert.doesNotMatch(taken.output, /staging\.yaml/); +}); + /** The repo's group `ci`, as 0.134.1 renders it empty; with `host` listed in it, the tenant's own edit, committed and pushed. */ async function listHost(repo: string, host: string): Promise { const hosts = join(repo, 'inventory', 'hosts.yml'); diff --git a/packages/lib/src/stack.test.ts b/packages/lib/src/stack.test.ts index 701e3caf..b33ec640 100644 --- a/packages/lib/src/stack.test.ts +++ b/packages/lib/src/stack.test.ts @@ -20,7 +20,10 @@ test('a stack is its compose file, its marker and a file for each environment th const result = await render(); assert.deepEqual(result.errors, []); assert.deepEqual(pathsOf(result), ['PLEXUS.md', 'compose.yaml', 'production.yaml', 'staging.yaml']); - for (const [path, origin] of result.files) assert.equal(origin.policy, 'born-once', path); + // The compose file and the marker are never re-synced; an environment's file is written at a birth alone, so that an + // update adds none to a stack that was born before the template had it. + for (const [path, origin] of result.files) + assert.equal(origin.policy, path.endsWith('.yaml') && path !== 'compose.yaml' ? 'birth-only' : 'born-once', path); assert.deepEqual(result.birth, []); }); From 687675fc9d3cf8af4df03cc37e0c8648f9cbcc32 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:10:55 +0100 Subject: [PATCH 87/91] The template stack's environment files are birth-only: an update adds none to a stack born without them Co-Authored-By: Claude Sonnet 5.5 --- templates/stack/template.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/templates/stack/template.yml b/templates/stack/template.yml index 7204b384..d97f5e98 100644 --- a/templates/stack/template.yml +++ b/templates/stack/template.yml @@ -49,8 +49,9 @@ questions: policies: # Every file is the stack's own from birth and never re-synced: the services of the compose file are the # person's, the marker's body is the stack's prose, its frontmatter is plx's, and an environment's file holds the - # person's host, values and pointers. + # person's host, values and pointers. An update never adds an environment's file to a stack that was born without + # it: the files are birth-only. PLEXUS.md.jinja: born-once compose.yaml.jinja: born-once - production.yaml.jinja: born-once - staging.yaml.jinja: born-once + production.yaml.jinja: birth-only + staging.yaml.jinja: birth-only From 9f84c5d75afffdf2b14935abd978af13dabea77e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:13:34 +0100 Subject: [PATCH 88/91] The update newborn test: a stack of 0.138.0 gets no environment file from an update, and one a person wrote stays Co-Authored-By: Claude Sonnet 5.5 --- newborns/update-released.test.ts | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/newborns/update-released.test.ts b/newborns/update-released.test.ts index 2607aff7..c2ff3f65 100644 --- a/newborns/update-released.test.ts +++ b/newborns/update-released.test.ts @@ -36,6 +36,9 @@ import { startRegistry } from './registry.ts'; const RELEASED = '0.134.1'; const FIRST = '0.135.0'; const SECOND = '0.136.0'; +// The released version whose template stack renders no environment file, and the one after it, packed here. +const STACKED = '0.138.0'; +const NEXT = '0.139.0'; const WORKSPACE = join(import.meta.dirname, '..'); const CLI = join(WORKSPACE, 'packages', 'cli'); @@ -93,11 +96,16 @@ before(async () => { mkdirSync(tarballs); // The released ones come from npm, the engine and the plx that bundles the templates it was born with. for (const name of ['cli-template', 'cli']) - execFileSync('npm', ['pack', `@plexus-ms/${name}@${RELEASED}`, '--registry', NPM, '--pack-destination', tarballs], { - cwd: here, - stdio: 'ignore', - }); - for (const version of [FIRST, SECOND]) packAs(version, tarballs); + for (const released of [RELEASED, STACKED]) + execFileSync( + 'npm', + ['pack', `@plexus-ms/${name}@${released}`, '--registry', NPM, '--pack-destination', tarballs], + { + cwd: here, + stdio: 'ignore', + }, + ); + for (const version of [FIRST, SECOND, NEXT]) packAs(version, tarballs); const registry = await startRegistry(tarballs); stop = registry.stop; const npmrc = join(here, 'npmrc.update'); @@ -143,7 +151,7 @@ esac`, GIT_CONFIG_VALUE_1: 'false', }; mkdirSync(env.HOME as string, { recursive: true }); - for (const version of [RELEASED, FIRST, SECOND]) + for (const version of [RELEASED, FIRST, SECOND, STACKED, NEXT]) await sh( 'npm', [ @@ -253,25 +261,25 @@ for (const kind of ['app', 'operations'] as const) { }); } -/** A stack of the released version in `repo`, at `stacks/docs`, with its files committed and pushed; the branch the repo is on. */ +/** A stack of version 0.138.0 in `repo`, at `stacks/docs`, with its files committed and pushed; the branch the repo is on. */ async function addStack(repo: string): Promise { - await sh('node', [plxOf(RELEASED), 'new', 'stacks/docs', 'stack', '-a', 'tenant=acme'], repo, env); + await sh('node', [plxOf(STACKED), 'new', 'stacks/docs', 'stack'], repo, env); await git(repo, 'add', '-A'); await git(repo, 'commit', '-q', '-m', 'a stack of the released version'); await sh('git', ['push', '-q', 'origin', 'main'], repo, env); } -test(`operations: a stack of ${RELEASED} gets no environment file from the update, which touches none the person wrote`, async () => { - const repo = await repoAt(RELEASED, 'operations'); +test(`operations: a stack of ${STACKED} gets no environment file from the update, which touches none the person wrote`, async () => { + const repo = await repoAt(STACKED, 'operations'); await addStack(repo); const written = 'host: deploy@own.example.com\nenv: {}\nsecrets: {}\n'; writeFileSync(join(repo, 'stacks', 'docs', 'production.yaml'), written); await git(repo, 'add', '-A'); await git(repo, 'commit', '-q', '-m', 'the production file, written by a person'); await sh('git', ['push', '-q', 'origin', 'main'], repo, env); - const taken = await take(FIRST, repo, FIRST); + const taken = await take(NEXT, repo, NEXT); assert.ok(taken.ok, taken.output); - const files = execFileSync('git', ['ls-tree', '--name-only', `plexus/${FIRST}`, 'stacks/docs/'], { + const files = execFileSync('git', ['ls-tree', '--name-only', `plexus/${NEXT}`, 'stacks/docs/'], { cwd: originOf(repo), encoding: 'utf8', }) From 4bc60e98022af61b07c257d4353c14d29e9ef08a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:30:16 +0100 Subject: [PATCH 89/91] plx deploy's test: a run that exits 0 and prints no Result line is a failure Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/deploy.test.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packages/cli/src/commands/deploy.test.ts b/packages/cli/src/commands/deploy.test.ts index d50fc65c..a93d64e7 100644 --- a/packages/cli/src/commands/deploy.test.ts +++ b/packages/cli/src/commands/deploy.test.ts @@ -374,6 +374,19 @@ test('plx deploy says what each stack came to: unchanged, rolled back, a run tha assert.equal(process.exitCode, 1); }); +test('a run that exits 0 and prints no Result line is a failure whatever its exit code', async () => { + // As ansible-playbook ends when a --limit or --skip-tags leaves it no task to run. + const f = fixture(); + writeFileSync(join(f.fake, 'outcome.docs'), 'exit 0 skipping: no hosts matched\n'); + const err = await plx(staging(f), f.fake); + assert.ok( + summary(err).includes('✗ docs-staging: failed: ansible-playbook exited 0: skipping: no hosts matched'), + err, + ); + assert.ok(summary(err).includes('✓ admin-staging: deployed'), 'the others ran'); + assert.equal(process.exitCode, 1); +}); + test('a stack whose deploy fails in the playbook is a failure with the playbook’s own line', async () => { const f = fixture(); writeFileSync(join(f.fake, 'outcome.docs'), "failed: 'Pull the images' failed (rc 1): pull access denied\n"); From f63ba7648f20a9a5ada4a6ac822d3a8aabbed1da Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:37:12 +0100 Subject: [PATCH 90/91] plx deploy's test: a path holding {{ or {% is refused before anything runs Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/deploy.test.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/packages/cli/src/commands/deploy.test.ts b/packages/cli/src/commands/deploy.test.ts index a93d64e7..a151a5fe 100644 --- a/packages/cli/src/commands/deploy.test.ts +++ b/packages/cli/src/commands/deploy.test.ts @@ -374,6 +374,26 @@ test('plx deploy says what each stack came to: unchanged, rolled back, a run tha assert.equal(process.exitCode, 1); }); +test('a checkout or scratch path holding {{ or {% is refused before anything runs, saying why: Ansible would template it', async () => { + for (const prefix of ['{{ 7 * 7 }}-', '{% x %}-']) { + const f = fixture(prefix); + await assert.rejects( + plx(staging(f), f.fake), + (e: unknown) => e instanceof UsageError && e.message.includes('Ansible') && e.message.includes(prefix), + ); + assert.equal(existsSync(join(f.fake, 'ansible.log')), false, 'no playbook ran'); + assert.equal(existsSync(join(f.fake, 'docker.log')), false, 'no registry was read'); + } + const f = fixture(); + const odd = join(f.root, 'tmp {{ x }}'); + mkdirSync(odd); + await assert.rejects( + plx(staging(f), f.fake, { TMPDIR: odd }), + (e: unknown) => e instanceof UsageError && e.message.includes('Ansible') && e.message.includes(odd), + ); + assert.equal(existsSync(join(f.fake, 'ansible.log')), false); +}); + test('a run that exits 0 and prints no Result line is a failure whatever its exit code', async () => { // As ansible-playbook ends when a --limit or --skip-tags leaves it no task to run. const f = fixture(); From 52862a6dda8d16c4a8d791dc91a51fe9da67e3c5 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:37:57 +0100 Subject: [PATCH 91/91] plx deploy refuses a path Ansible would template; the doctor's removed requirements are listed by module and suffix Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/deploy.ts | 13 +++++++++++++ packages/lib/src/doctor.ts | 19 +++++++++++++------ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/packages/lib/src/deploy.ts b/packages/lib/src/deploy.ts index b2a3e028..94fc980f 100644 --- a/packages/lib/src/deploy.ts +++ b/packages/lib/src/deploy.ts @@ -215,6 +215,7 @@ export async function deploy(ctx: Context, options: DeployOptions): Promise ({ stack: s, file: s.environments.find((e) => e.name === environment) })); refuseFiles(repo.root, named, environment); refuseMissingToken(repo.root, named); + refuseTemplated([repo.root, ...named.flatMap(({ file }) => (file ? [file.file] : [])), tmpdir()]); const legs = named.flatMap(({ stack, file }): Leg[] => file ? [{ stack: stack.name, file: file.file, host: file.host as string }] : [], ); @@ -344,6 +345,18 @@ function refuseFiles( throw new UsageError(`${lines.join('\n')}\nno stack was deployed into ${environment}; plx doctor reports the same`); } +/** + * Ansible templates a path it is given that holds `{{` or `{%`, on the deployer, so that the file it looks for is + * not the one named: a checkout, a file or the scratch directory with either in its path is refused. + */ +function refuseTemplated(paths: string[]): void { + const bad = paths.filter((path) => /\{[{%]/.test(path)); + if (bad.length > 0) + throw new UsageError( + `${bad.join(', ')} holds \`{{\` or \`{%\`, which Ansible would template on this machine, so the playbook would read another path: move the checkout, or set TMPDIR elsewhere; nothing ran`, + ); +} + /** * In CI, where the playbook resolves pointers with the repository's secret * `DEPLOY_VAULT_TOKEN` as OP_SERVICE_ACCOUNT_TOKEN, a run with pointers and diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 46571237..24ac3f01 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -703,11 +703,18 @@ const MOVED_TO_STACK = new Set([ /** What a requirement that was renamed as it moved is called now. */ const RENAMED_ON_MOVE: Readonly> = { NoCommittedValues: 'NoCommittedSecrets' }; -/** - * Requirements the standard removed: a deviation under one of them can go, whatever an index of an earlier version - * says. Joined at run time, as a removed name is no citation of the compendium's. - */ -const REMOVED = new Set([['PLX-Stack', 'PathPrefix'].join('/'), ['PLX-Ingress', 'PrefixInRecord'].join('/')]); +/** Requirements the standard removed, by module and suffix: a deviation under one of them can go, whatever an index of an earlier version says. */ +const REMOVED: Readonly>> = { + 'PLX-Stack': new Set(['PathPrefix']), + 'PLX-Ingress': new Set(['PrefixInRecord']), +}; + +/** Whether the standard removed the requirement `name`. */ +function removed(name: string): boolean { + const slash = name.indexOf('/'); + const module = name.slice(0, slash); + return slash > 0 && Object.hasOwn(REMOVED, module) && (REMOVED[module]?.has(name.slice(slash + 1)) ?? false); +} /** What a released `PLX-Stack/…` name is called now, where it was renamed; the `PLX-App/…` form is `movedTo`'s. */ function renamedInStack(name: string): string | undefined { @@ -804,7 +811,7 @@ function diagnoseUnit(unit: Facts, known: Set): UnitReport { requirement: name, problem: `listed under \`deviations\`, but no requirement has this name: it is now \`${renamedInStack(name)}\``, }); - else if (REMOVED.has(name)) + else if (removed(name)) findings.push({ requirement: name, problem: 'listed under `deviations`, but this requirement was removed from the standard: the deviation can go',