diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile index 16a11007..7895b404 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile +++ b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile @@ -13,7 +13,8 @@ # # the runner GitHub's Actions runner and the libraries it needs, run # as the user runner (1001), with sudo where the engine -# allows it (a slot's no-new-privileges does not) +# allows it (a slot's container, which ci-runner-slot +# starts with no capability, does not) # node, pnpm node from the base; pnpm and yarn through corepack, at # the version a repo's packageManager names, downloaded # into ~/.cache/node/corepack diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml b/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml index 471f8c81..11935c73 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml +++ b/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml @@ -1,10 +1,12 @@ # The tools the environment image carries (Dockerfile beside this file), as # mise's system config, /etc/mise/config.toml: the lowest of mise's configs, so # that a repo's own pin of any of them wins. Installed at build time into mise's -# system directory, which mise searches after its data directory and never -# writes; a version a repo pins and the image lacks installs into the data -# directory, which a runner host shares between its repo slots; in -# a delivery slot it stays in the job's container. +# system directory, which mise searches after its data directory and which only +# root can write; a version a repo pins and the image lacks installs into the +# data directory, which a runner host shares between its repo slots; in +# a delivery slot it stays in the job's container. A job's `mise use` that names +# a version installed here makes mise rebuild the shims here, through sudo, +# which fails in a slot: the job deploy has it write them elsewhere. [tools] # plx-ci at the Plexus version: the pin is written with each version, never by # the update bot (§ 1 PLX-Updates); allow_low_downloads only waives npm's diff --git a/newborns/deploy-job.test.ts b/newborns/deploy-job.test.ts index 4152436d..868a44aa 100644 --- a/newborns/deploy-job.test.ts +++ b/newborns/deploy-job.test.ts @@ -13,22 +13,30 @@ // option of the tool node and of plx, node and plx as `path:` versions, an asdf plugin for node, the // settings that send node's download elsewhere, a .miserc.toml that undoes the job's ignoring of the // repo's config, and a tool option of a nested project; and, with a system config as a runner image has it, the -// plx-ci the later steps run and the file tasks of the checkout. The step of the job repo, run the same way, is -// the control: it runs the hook, exports the variable and installs the other tool, which is what shows -// that a probe can fire. +// plx-ci the later steps run and the file tasks of the checkout; and the steps as a delivery slot runs +// them, in a container of the environment image (`slotImage`), whose mise system directory is root's. +// The step of the job repo, run the same way, is the control: it runs the hook, exports the variable +// and installs the other tool, which is what shows that a probe can fire. // -// Every case has data, state and system directories of its own, and a home: nothing of what the -// machine's own mise holds is in the way, and what the case installs is installed into it alone; mise -// itself is the one download, made once and linked in. What this does not stand in for: the runner's own -// program (it passes the inputs, orders the path and masks values), and a runner of the forge. It needs -// the network: the action's source from the forge, mise from its releases, node, and the registry. +// Every case but the slot's has data, state and system directories of its own, and a home: nothing of +// what the machine's own mise holds is in the way, and what the case installs is installed into it +// alone; mise itself is the one download, made once and linked in, and copied into the slot's +// container. What this does not stand in for: the runner's own program (it passes the inputs, orders +// the path and masks values), and a runner of the forge. It needs the network: the action's source +// from the forge, mise from its releases, node, and the registry. The slot's case also needs Docker, +// and builds its image as the image's own build does, from Docker Hub (the base), Debian's mirror, +// mise's releases (the image's pin) and npm (the image's plx-ci), registries the other newborns use +// as well; the image is kept, so a warm run builds from Docker's cache and downloads only node. +// The case took two minutes cold, with the base image already present, and between 15 seconds and +// three minutes warm, as fast as node's download. import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; import { chmodSync, cpSync, existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; import { createServer, type Server } from 'node:http'; -import { join } from 'node:path'; +import { basename, join } from 'node:path'; import { after, before, test } from 'node:test'; import { parse } from 'yaml'; -import { born, builtVersion, close, git, open, put, sh, tryRun } from './helpers.ts'; +import { born, builtVersion, close, git, open, put, type Ran, sh, tryRun } from './helpers.ts'; /** The variable the repo's [env] sets: what the job deploy must not export. */ const VARIABLE = 'PLX_DEPLOY_JOB_PROBE'; @@ -55,6 +63,8 @@ let control: Step; let requests = 0; let mirror: Server | undefined; let mirrorUrl = ''; +/** The delivery slot's container (`slot`), which `after` removes. */ +let slotContainer = ''; before(async () => { here = await open('deploy-job'); @@ -91,11 +101,12 @@ before(async () => { }); after(async () => { + if (slotContainer) await tryRun('docker', ['rm', '-f', slotContainer], here); await new Promise((resolve) => (mirror ? mirror.close(resolve) : resolve(undefined))); await close(); }); -/** The expressions the workflow's inputs and environment hold; any other fails here. */ +/** The expressions the workflow's inputs and environment hold, each where it stands in a value; any other fails here. */ function evaluated(value: unknown, workspace: string, temp = ''): string { if (typeof value !== 'string' || !value.includes('${{')) return String(value); const known: Record = { @@ -103,11 +114,17 @@ function evaluated(value: unknown, workspace: string, temp = ''): string { '${{ github.workspace }}': workspace, '${{ runner.temp }}': join(temp, 'temp'), }; - const found = known[value]; - assert.ok(found !== undefined, `an expression this test does not know: ${value}`); - return found; + return value.replace(/\$\{\{.*?\}\}/g, (expression) => { + const found = known[expression]; + assert.ok(found !== undefined, `an expression this test does not know: ${expression}`); + return found; + }); } +/** A step's own environment, its expressions evaluated. */ +const stepEnv = (step: Step, workspace: string, temp: string): NodeJS.ProcessEnv => + Object.fromEntries(Object.entries(step.env ?? {}).map(([key, value]) => [key, evaluated(value, workspace, temp)])); + /** The lines of a runner's file command: `NAME=value`, or `NAME< { const out: Record = {}; @@ -187,15 +204,31 @@ function actionEnv(dir: string, temp: string, inputs: Record): }; } +/** Where a job's steps run: this machine, with the case's own directories, or a slot's container (`slot`). */ +interface Machine { + /** What every step's environment starts from. */ + env: NodeJS.ProcessEnv; + /** The PATH the runner hands a step, behind what the steps put in front of it. */ + path: string; + exec(command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv): Promise; +} + +/** This machine, the case's directories in place of mise's own. */ +const host = (name: string, extra: NodeJS.ProcessEnv = {}): Machine => ({ + env: { ...worldOf(name), ...extra }, + path: process.env.PATH ?? '', + exec: (command, args, cwd, env) => tryRun(command, args, cwd, env), +}); + interface After { /** The environment a later step runs in: the job's, what the steps exported, and the path they gave. */ env: NodeJS.ProcessEnv; dir: string; + machine: Machine; } /** The steps, as a job runs them in `dir` up to its setup step, then what a later step finds. */ -async function run(dir: string, job: Job, name: string, extra: NodeJS.ProcessEnv = {}): Promise { - const world = { ...worldOf(name), ...extra }; +async function run(dir: string, job: Job, name: string, machine: Machine = host(name)): Promise { const temp = join(here, 'cases', name, 'runner'); const jobEnv = Object.fromEntries(Object.entries(job.env ?? {}).map(([key, value]) => [key, evaluated(value, dir)])); const files = { env: join(temp, 'env'), path: join(temp, 'path') }; @@ -203,27 +236,31 @@ async function run(dir: string, job: Job, name: string, extra: NodeJS.ProcessEnv const next = (): NodeJS.ProcessEnv => { const path = existsSync(files.path) ? readFileSync(files.path, 'utf8').split('\n').filter(Boolean).reverse() : []; const exported = existsSync(files.env) ? entries(files.env) : {}; - return { ...world, ...jobEnv, ...exported, PATH: [...path, process.env.PATH].join(':') }; + return { ...machine.env, ...jobEnv, ...exported, PATH: [...path, machine.path].join(':') }; }; for (const step of job.steps) { if (step.uses?.startsWith('actions/checkout')) continue; if (step.id === 'setup') break; if (step.uses) { - const env = { ...next(), ...actionEnv(dir, temp, step.with ?? {}), ...step.env }; - const ran = await tryRun('node', [join(action, 'dist', 'index.js')], dir, env); + const env = { ...next(), ...actionEnv(dir, temp, step.with ?? {}), ...stepEnv(step, dir, temp) }; + const ran = await machine.exec('node', [join(action, 'dist', 'index.js')], dir, env); assert.ok(ran.ok, ran.output); } else { const cwd = step['working-directory'] ? evaluated(step['working-directory'], dir, temp) : dir; mkdirSync(cwd, { recursive: true }); - const ran = await tryRun('sh', ['-c', step.run ?? ''], cwd, { ...next(), ...step.env }); + const ran = await machine.exec('sh', ['-c', step.run ?? ''], cwd, { ...next(), ...stepEnv(step, dir, temp) }); assert.ok(ran.ok, `${step.run}\n${ran.output}`); } } - return { env: next(), dir }; + return { env: next(), dir, machine }; } /** What a later step prints for a shell command, in the checkout. */ -const later = async (after: After, command: string) => (await sh('sh', ['-c', command], after.dir, after.env)).trim(); +async function later(after: After, command: string): Promise { + const ran = await after.machine.exec('sh', ['-c', command], after.dir, after.env); + assert.ok(ran.ok, `${command}\n${ran.output}`); + return ran.output.trim(); +} /** A file a case's code would write, which must not exist. */ const probe = (name: string) => join(here, 'probes', name); @@ -325,11 +362,209 @@ const IMAGE_VERSION = '9.9.9'; test('on a slot the plx-ci the later steps run is the one the workflow names, not the runner image’s', async () => { const name = 'image-plx-ci'; const dir = copyOf(name); - const after = await run(dir, deploy, name, slotSystem(name)); + const after = await run(dir, deploy, name, host(name, slotSystem(name))); assert.equal(await later(after, 'plx-ci --version'), builtVersion()); assert.equal(await later(after, 'plx --version'), builtVersion()); }); +const IMAGE_DIR = join(import.meta.dirname, '..', 'ansible', 'ci', 'roles', 'actions_runners', 'files', 'ci-runner'); +/** The slot's image, tagged by what it is built from (`slot`) and kept between runs, so that a warm run builds nothing. */ +const SLOT_IMAGE = 'plx-newborn-deploy-job-slot'; +/** How long a slot's container lives at most, so that one a killed run leaves goes by itself. */ +const SLOT_LIFETIME = 30 * 60; + +/** + * The environment image as far as the step that installs plx meets it, built from the image's own Dockerfile and + * mise.toml (`slotImage`). Taken over word for word, in their order, the Dockerfile's instructions that make what the + * step meets: its base, every ENV, the apt-get install that brings sudo, curl and zstd, the user runner and the + * sudoers line out of the instruction that creates them, the download of mise at its pin into /usr/local/bin, the copy + * of mise.toml as the system config, the line that installs and shims the system tools as root, USER and WORKDIR. The + * system config is the image's own [settings] block and its plx-ci line. Left out on purpose: the Actions runner, + * docker's client, the browsers' libraries, corepack and ci-mise-install, none of which the step runs (`LEFT_OUT`), and + * the system config's other tools (the vault's CLI, gh, exo), which the step does not name: plx-ci alone is enough for + * mise to rebuild the system shims. A line the test takes that the Dockerfile no longer has fails the test, and so + * does a RUN, COPY or ADD of the Dockerfile that it neither takes nor leaves out by name. + */ +const LEFT_OUT: Record = { + "docker's client": /^RUN curl [^\n]*docker\.tgz/, + "the browsers' libraries": /playwright@[^\n]* install-deps/, + corepack: /^RUN corepack enable$/, + 'ci-mise-install': /^COPY [^\n]*ci-mise-install /, +}; + +function slotImage(): { dockerfile: string; config: string } { + const text = readFileSync(join(IMAGE_DIR, 'Dockerfile'), 'utf8'); + // The instructions, each with its continuation lines, comments and blank lines dropped. + const instructions: string[] = []; + let current = ''; + for (const line of text.split('\n')) { + if (!current && (/^\s*#/.test(line) || !line.trim())) continue; + current += current ? `\n${line}` : line; + if (!line.endsWith('\\')) { + instructions.push(current); + current = ''; + } + } + const taken = new Map(); + const take = (what: string, instruction: string) => { + taken.set(what, (taken.get(what) ?? 0) + 1); + return instruction; + }; + const kept: string[] = []; + for (const instruction of instructions) { + const before = kept.length; + if (/^(FROM|ENV|USER|WORKDIR) /.test(instruction)) + kept.push(take(instruction.split(' ')[0] as string, instruction)); + else if (/^ARG MISE_(VERSION|SHA256)=/.test(instruction)) kept.push(take('ARG MISE_*', instruction)); + else if (/^RUN apt-get update[\s\S]*apt-get install[\s\S]*\bsudo\b/.test(instruction)) + kept.push(take('the apt-get install of sudo', instruction)); + else if (/^RUN .*\/usr\/local\/bin\/mise "https:/.test(instruction)) + kept.push(take('the download of mise', instruction)); + else if (instruction === 'COPY mise.toml /etc/mise/config.toml') kept.push(take('the system config', instruction)); + else if (/^RUN mise install --system/.test(instruction)) kept.push(take('the system install', instruction)); + else if (/useradd .* runner\b/.test(instruction)) { + const user = /useradd [^&;]*runner/.exec(instruction)?.[0]; + const sudoers = /echo '[^']*' >\/etc\/sudoers\.d\/runner/.exec(instruction)?.[0]; + if (user && sudoers) kept.push(take('the user runner and sudoers', `RUN ${user} && ${sudoers}`)); + } + if (kept.length === before && /^(RUN|COPY|ADD) /.test(instruction)) + assert.ok( + Object.values(LEFT_OUT).some((pattern) => pattern.test(instruction)), + `an instruction of the image's Dockerfile this test neither takes nor leaves out:\n${instruction}`, + ); + } + for (const what of [ + 'FROM', + 'ENV', + 'USER', + 'WORKDIR', + 'ARG MISE_*', + 'the apt-get install of sudo', + 'the download of mise', + 'the system config', + 'the system install', + 'the user runner and sudoers', + ]) + assert.ok(taken.has(what), `the image's Dockerfile no longer has ${what} as this test takes it`); + const toml = readFileSync(join(IMAGE_DIR, 'mise.toml'), 'utf8'); + const settings = /^\[settings\]\n(?:(?!\[)[^\n]*\n?)*/m.exec(toml)?.[0]; + const pin = /^"npm:@plexus-ms\/cli-ci" = .*$/m.exec(toml)?.[0]; + assert.ok(settings && pin, "the image's mise.toml has a [settings] block and pins plx-ci"); + return { dockerfile: `${kept.join('\n')}\n`, config: `[tools]\n${pin}\n\n${settings}` }; +} + +/** + * A delivery slot of a runner host, as ci-runner-slot starts one: a container of the image (`slotImage`) on the host's + * network, as the user runner, with no capability (which ci-runner-slot must still give), so that sudo fails as it does + * there. Mounted of the host's is only + * what this file must hand a step: the case's own directory, the action's source, the registry's npmrc, and the mise + * the action downloaded in `before`, which is copied to where the action keeps it, so that the action verifies it and + * downloads no mise, only its signed checksums. The container is named for the run's directory, lives `SLOT_LIFETIME` + * at most and is removed by `after`. The image is tagged by a hash of its Dockerfile and config, so that two checkouts + * with different Dockerfiles do not test each other's image, and the older tags of its name are removed where no + * container uses them. + */ +async function slot(name: string): Promise { + const root = join(here, 'cases', name); + const temp = join(root, 'runner'); + // The runner's directories and file commands, written by the steps as the user runner. + for (const sub of ['temp', 'tool-cache']) mkdirSync(join(temp, sub), { recursive: true }); + for (const file of ['env', 'path', 'output', 'state']) writeFileSync(join(temp, file), ''); + await sh('chmod', ['-R', 'a+rwX', root], here); + assert.match( + readFileSync(join(IMAGE_DIR, '..', 'ci-runner-slot'), 'utf8'), + /--cap-drop ALL/, + 'ci-runner-slot starts a slot with no capability, as this test does', + ); + const { dockerfile, config } = slotImage(); + put(here, { 'slot-image/Dockerfile': dockerfile, 'slot-image/mise.toml': config }); + const tag = createHash('sha256').update(dockerfile).update('\0').update(config).digest('hex').slice(0, 16); + const image = `${SLOT_IMAGE}:${tag}`; + const tags = await sh('docker', ['images', SLOT_IMAGE, '--format', '{{.Tag}}'], here); + for (const old of tags.split('\n').filter((other) => other && other !== tag)) + await tryRun('docker', ['rmi', `${SLOT_IMAGE}:${old}`], here); + await sh('docker', ['build', '-q', '-t', image, join(here, 'slot-image')], here); + const npmrc = join(here, 'npmrc'); + const seed = join(here, 'mise-data', 'bin'); + const mounts = [ + `${root}:${root}`, + `${action}:${action}:ro`, + `${seed}:${seed}:ro`, + ...(existsSync(npmrc) ? [`${npmrc}:${npmrc}:ro`] : []), + ]; + slotContainer = `${basename(here)}-slot`; + await sh( + 'docker', + [ + 'run', + '-d', + '--rm', + '--init', + '--name', + slotContainer, + '--network', + 'host', + '--cap-drop', + 'ALL', + '--memory', + '2g', + ...mounts.flatMap((mount) => ['-v', mount]), + image, + 'sleep', + String(SLOT_LIFETIME), + ], + here, + ); + await sh( + 'docker', + ['exec', slotContainer, 'sh', '-c', `mkdir -p ~/.local/share/mise/bin && cp -a ${seed}/. ~/.local/share/mise/bin/`], + here, + ); + const path = (await sh('docker', ['exec', slotContainer, 'printenv', 'PATH'], here)).trim(); + return { + env: existsSync(npmrc) ? { NPM_CONFIG_USERCONFIG: npmrc } : {}, + path, + exec: (command, args, cwd, env) => + tryRun( + 'docker', + [ + 'exec', + '-w', + cwd, + ...Object.entries(env).flatMap(([key, value]) => (value === undefined ? [] : ['-e', `${key}=${value}`])), + slotContainer, + command, + ...args, + ], + here, + ), + }; +} + +// The step as a delivery slot runs it: the image's plx-ci is the version the workflow names, since a version stamps both, +// so mise finds it installed in the system directory and rebuilds the system shims, which point at the image's mise and +// not at the one the action downloads; only root can write them, and sudo fails in a container without capabilities. +// It downloads, cold: the image's base and Debian's packages, mise at the image's pin from its releases, and the +// image's plx-ci with its dependencies from npm, as the image's own build does; in the container node from its +// project. Warm, the image is built from Docker's cache and node is the one download. +test('on a delivery slot, in a container of the environment image, the job deploy installs plx at the version the workflow names', async () => { + const name = 'delivery-slot'; + const pin = /^"npm:@plexus-ms\/cli-ci" = \{ version = "([^"]+)"/m.exec( + readFileSync(join(IMAGE_DIR, 'mise.toml'), 'utf8'), + )?.[1]; + assert.equal(pin, builtVersion(), "the image's plx-ci is the version the workflow names: a version stamps both"); + const dir = copyOf(name); + const machine = await slot(name); + try { + const after = await run(dir, deploy, name, machine); + assert.equal(await later(after, 'plx --version'), builtVersion()); + assert.equal(await later(after, 'plx-ci --version'), builtVersion()); + } finally { + // What the user runner wrote into the case's directory, for `close` to remove. + await tryRun('docker', ['exec', slotContainer, 'chmod', '-R', 'a+rwX', join(here, 'cases', name)], here); + } +}); + // A file task in the checkout is a config file mise must trust before it reads it, and a job that ignores the // checkout's config cannot trust it: the step failed on the slot, whose image sets `paranoid = ["config"]` (tried: the // same repo passed on a host with no such setting, and failed there with MISE_PARANOID=1), so a repo's author could @@ -341,7 +576,7 @@ for (const directory of ['.mise/tasks', 'mise-tasks', '.config/mise/tasks']) mkdirSync(join(dir, directory), { recursive: true }); writeFileSync(join(dir, directory, 'x'), `#!/bin/sh\ntouch ${probe(name)}\n`); chmodSync(join(dir, directory, 'x'), 0o755); - const after = await run(dir, deploy, name, slotSystem(name)); + const after = await run(dir, deploy, name, host(name, slotSystem(name))); assert.ok(!existsSync(probe(name)), 'the task ran'); assert.equal(await later(after, 'plx --version'), builtVersion()); }); diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index a2de7de8..fc827f08 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -200,6 +200,9 @@ test('the job deploy reads no mise.toml of the repo: its config paths are ignore const tool = (name: string) => `'npm:@plexus-ms/${name}[allow_low_downloads=true]@${VERSION}'`; assert.equal(deploy?.steps?.[2]?.['working-directory'], '${{ runner.temp }}'); assert.equal(deploy?.steps?.[2]?.run, `mise use -g node@${node} ${tool('cli')} ${tool('cli-ci')}`); + // On a slot mise finds the image's plx-ci at this version and rebuilds the image's shims, which only root can + // write: the step's are written into its own temp directory. + assert.deepEqual(deploy?.steps?.[2]?.env, { MISE_SYSTEM_SHIMS_DIR: '${{ runner.temp }}/mise-system-shims' }); assert.deepEqual( stepsOf(deploy) .slice(0, 3) 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 05e43ec7..116f0aee 100644 --- a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja @@ -106,6 +106,8 @@ jobs: # checkout, and installs plx and what it runs on from the versions named here. # The install step runs outside the checkout, whose file tasks mise would have to trust; the action puts no # tool directory of the runner image ahead of the shims, so the tools run are the ones installed here. + # On a runner host's slot the image's plx-ci is the one named here, so mise rebuilds the image's shims, which only + # root can write; the step has it write them into its own temp directory, which nothing runs from. env: MISE_IGNORED_CONFIG_PATHS: ${{ github.workspace }} steps: @@ -116,6 +118,8 @@ jobs: cache: false export_path: false - working-directory: ${{ runner.temp }} + 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 %}' - id: setup{% endraw %}{% if ci_service_account %}{% raw %} env: