diff --git a/packages/cli-ci/package.json b/packages/cli-ci/package.json index d64de60c..c416a8db 100644 --- a/packages/cli-ci/package.json +++ b/packages/cli-ci/package.json @@ -1,7 +1,7 @@ { "name": "@plexus-ms/cli-ci", "version": "0.134.1", - "description": "plx-ci, the CI verbs of Plexus: the plan of a run, the publish of an app's image, throwaway runners on a cloud and their teardown", + "description": "plx-ci, the CI verbs of Plexus: the setup of a job, the plan of a run, the publish of an app's image, throwaway runners on a cloud and their teardown", "license": "GPL-3.0-or-later", "type": "module", "bin": { diff --git a/packages/cli-ci/src/commands/index.ts b/packages/cli-ci/src/commands/index.ts index b79524b9..767aa343 100644 --- a/packages/cli-ci/src/commands/index.ts +++ b/packages/cli-ci/src/commands/index.ts @@ -1,7 +1,8 @@ // Every command of plx-ci, in the order `plx-ci --help` lists them. Same rule // as plx: a command module maps argv onto core/ and nothing more, and the // logic, the planning and the tests live in core/. The universal commands -// come first, in the order a run uses them, and read the strategy; `hybrid` +// come first, in the order a run uses them: setup prepares a job, and the +// others read the strategy; `hybrid` // holds what only that strategy needs. The display versions, opt-in per // repo, read no strategy and sit where a release uses them, after publish. import type { Command } from 'commander'; @@ -9,5 +10,6 @@ import { register as displayVersions } from './displayVersions.ts'; import { register as hybrid } from './hybrid.ts'; import { register as plan } from './plan.ts'; import { register as publish } from './publish.ts'; +import { register as setup } from './setup.ts'; -export const commands: ((program: Command) => void)[] = [plan, publish, displayVersions, hybrid]; +export const commands: ((program: Command) => void)[] = [setup, plan, publish, displayVersions, hybrid]; diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts new file mode 100644 index 00000000..f3c17f3b --- /dev/null +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -0,0 +1,390 @@ +// plx-ci setup as a job of the forge runs it: a process with the forge's +// 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'; +import { runJob } from '../testing/job.ts'; + +const KEY_REF = 'op://acme-ci/repo_web/server-actions-key'; +const KEY = 'c2VydmVyLWFjdGlvbnMta2V5LWZvci10ZXN0cw=='; + +/** What the vault acme-ci holds for a repo job. */ +const VAULT = { [KEY_REF]: KEY }; + +const CONNECT = { OP_CONNECT_HOST: 'http://localhost:8080', OP_CONNECT_TOKEN: 'connect-token' }; +const SERVICE_ACCOUNT = { OP_SERVICE_ACCOUNT_TOKEN: 'ops_service-account' }; + +/** The vault's credentials each `op` call saw. */ +const credentialsOf = (calls: ReturnType['calls']) => + calls + .filter((c) => c.tool === 'op') + .map((c) => + Object.keys(c.seen) + .filter((k) => k.startsWith('OP_')) + .sort(), + ); + +test('with the runner’s Connect server, the vault is read through it', () => { + const job = runJob(['repo'], { env: CONNECT, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.deepEqual(credentialsOf(job.calls), [['OP_CONNECT_HOST', 'OP_CONNECT_TOKEN']]); + assert.match(job.log, /through the runner’s Connect server/); +}); + +test('without one, the vault is read with the service account', () => { + const job = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.deepEqual(credentialsOf(job.calls), [['OP_SERVICE_ACCOUNT_TOKEN']]); + assert.match(job.log, /with the service account/); +}); + +test('with both, the Connect server alone: op never sees the service account’s token', () => { + const job = runJob(['repo'], { env: { ...CONNECT, ...SERVICE_ACCOUNT }, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.deepEqual(credentialsOf(job.calls), [['OP_CONNECT_HOST', 'OP_CONNECT_TOKEN']]); +}); + +test('a Connect server’s address without its token is no Connect server', () => { + const job = runJob(['repo'], { env: { OP_CONNECT_HOST: CONNECT.OP_CONNECT_HOST, ...SERVICE_ACCOUNT }, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.deepEqual(credentialsOf(job.calls), [['OP_SERVICE_ACCOUNT_TOKEN']]); +}); + +test('with neither, the job fails in one line that names both, and nothing is read', () => { + const job = runJob(['repo'], { 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/); + assert.match(job.log, /OP_SERVICE_ACCOUNT_TOKEN/); +}); + +test('an item the vault does not hold fails the job, naming the reference', () => { + const job = runJob(['repo'], { env: CONNECT, vault: {} }); + assert.equal(job.status, 1, job.log); + assert.match(job.log, /op:\/\/acme-ci\/repo_web\/server-actions-key/); +}); + +/** The lines of a job's log before the first that is no mask. */ +const masksFirst = (log: string): string[] => { + const lines = log.split('\n'); + return lines.slice( + 0, + lines.findIndex((l) => !l.startsWith('::add-mask::')), + ); +}; + +test('a repo job hands the server-actions key to later steps as an output, masked before anything is printed', () => { + const job = runJob(['repo'], { env: CONNECT, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.equal(job.output['server-actions-key'], KEY); + assert.ok(masksFirst(job.log).includes(`::add-mask::${KEY}`), job.log); + assert.equal(job.log.split(KEY).length, 2, 'the key is in the log once, in its mask'); +}); + +test('the server-actions key is in no variable of the job', () => { + const job = runJob(['repo', '--private-packages'], { env: SERVICE_ACCOUNT, vault: VAULT }); + assert.equal(job.status, 0, job.log); + for (const [name, value] of Object.entries(job.env)) assert.ok(!value.includes(KEY), name); +}); + +test('a repo job is logged in to the forge’s image registry with its own token, in a Docker config of the job’s own', () => { + const job = runJob(['repo'], { env: CONNECT, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.deepEqual(Object.keys(job.env), ['DOCKER_CONFIG']); + assert.equal(job.env.DOCKER_CONFIG, join(job.temp, 'docker')); + const config = JSON.parse(readFileSync(join(job.temp, 'docker', 'config.json'), 'utf8')); + const auth = Buffer.from('octocat:ghs_job').toString('base64'); + assert.deepEqual(config, { auths: { 'ghcr.io': { auth } } }); + assert.ok(masksFirst(job.log).includes(`::add-mask::${auth}`), 'the job’s token, encoded, is masked as the token is'); +}); + +test('a repo job that installs private packages is logged in to the forge’s package registry too', () => { + const job = runJob(['repo', '--private-packages'], { env: CONNECT, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.equal(job.env.NPM_CONFIG_USERCONFIG, join(job.temp, 'npm', 'npmrc')); + assert.equal(readFileSync(join(job.temp, 'npm', 'npmrc'), 'utf8'), '//npm.pkg.github.com/:_authToken=ghs_job\n'); +}); + +test('the logins are the job’s alone: each file 0600 in a directory 0700', () => { + const job = runJob(['repo', '--private-packages'], { env: CONNECT, vault: VAULT }); + assert.equal(job.status, 0, job.log); + const config = join(job.env.DOCKER_CONFIG ?? '', 'config.json'); + const npmrc = job.env.NPM_CONFIG_USERCONFIG ?? ''; + const modes = [dirname(config), config, dirname(npmrc), npmrc].map((path) => statSync(path).mode & 0o777); + assert.deepEqual(modes, [0o700, 0o600, 0o700, 0o600]); +}); + +test('under --dry-run the vault is read and masked, and nothing is handed or written', () => { + const job = runJob(['--dry-run', 'repo', '--private-packages'], { env: CONNECT, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.ok(masksFirst(job.log).includes(`::add-mask::${KEY}`), job.log); + assert.deepEqual([job.output, job.env], [{}, {}]); + assert.deepEqual(readdirSync(job.temp), []); +}); + +const SSH_KEY = [ + '-----BEGIN OPENSSH PRIVATE KEY-----', + 'b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW', + 'QyNTUxOQAAACDfakefakefakefakefakefakefakefakefakefakefakeAAAA', + '-----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(), +}; + +test('a deploy job’s SSH agent holds the deploy key, and the agent’s socket is the one variable of the job', () => { + const job = runJob(['deploy'], { env: CONNECT, vault: DEPLOY_VAULT }); + assert.equal(job.status, 0, job.log); + const socket = join(job.temp, 'ssh-agent.sock'); + assert.deepEqual(job.env, { SSH_AUTH_SOCK: socket }); + assert.deepEqual(job.calls.find((c) => c.tool === 'ssh-agent')?.args, ['-a', 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 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 }); + 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 }); + 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')]) { + 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`); + } + assert.ok( + lines.some((l) => !l.startsWith('::add-mask::') && l.includes(SSH_KEY.split('\n')[1] ?? '')), + 'the key’s input is shown with -v, which is what the masks are for', + ); +}); + +/** 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 }); + assert.equal(job.status, 0, job.log); + assert.deepEqual( + job.calls.map((c) => c.tool), + ['op', 'op', 'op'], + ); + 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. */ +const CACHE_HOST = { PLX_TURBO_CACHE_HOST: 'cache.acme.internal' }; +const SETUP_KEY = 'nb-setup-key-0123456789'; +const OVERLAY_VAULT = { + 'op://acme-ci/netbird/setup-key': SETUP_KEY, + 'op://acme-ci/turbo-cache/shared-token': 'shared-token-0123456789', + 'op://acme-ci/turbo-cache/trusted-token': 'trusted-token-0123456789', +}; +const opReads = (job: ReturnType) => job.calls.filter((c) => c.tool === 'op').map((c) => c.args[1]); + +test('on a forge runner, a repo job of a repo with a cache host on netbird joins the overlay and is handed both caches’ tokens', () => { + const job = runJob(['repo', '--overlay', 'netbird'], { + env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...CACHE_HOST }, + vault: { ...VAULT, ...OVERLAY_VAULT }, + }); + assert.equal(job.status, 0, job.log); + assert.deepEqual(job.env, { + DOCKER_CONFIG: join(job.temp, 'docker'), + PLX_TURBO_SHARED_TOKEN: 'shared-token-0123456789', + PLX_TURBO_TRUSTED_TOKEN: 'trusted-token-0123456789', + }); + assert.equal(job.output.joined, 'true'); + for (const secret of [SETUP_KEY, 'shared-token-0123456789', 'trusted-token-0123456789']) + assert.ok(masksFirst(job.log).includes(`::add-mask::${secret}`), secret); + const up = job.calls.find((c) => c.tool === 'netbird' && c.args[0] === 'up'); + assert.deepEqual([up?.args, up?.seen.NB_SETUP_KEY], [['up', '--hostname', 'ci-41-repo'], SETUP_KEY]); + assert.ok( + job.calls.some((c) => c.tool === 'apt-get' && c.args.some((a) => /^netbird=\d+\.\d+\.\d+$/.test(a))), + 'the client at a pinned version', + ); + assert.deepEqual(job.calls.find((c) => c.tool === 'getent')?.args, ['hosts', 'cache.acme.internal']); +}); + +test('on a slot a job joins nothing and reads no cache token: the slot is on the overlay and carries its host’s', () => { + for (const args of [ + ['repo', '--overlay', 'netbird'], + ['deploy', '--overlay', 'netbird'], + ]) { + const job = runJob(args, { + env: { ...CONNECT, ...SLOT, ...CACHE_HOST }, + vault: { ...VAULT, ...DEPLOY_VAULT, ...OVERLAY_VAULT }, + }); + assert.equal(job.status, 0, job.log); + assert.ok(!job.calls.some((c) => c.tool === 'netbird' || c.tool === 'sudo'), args[0]); + assert.ok(!opReads(job).some((ref) => /netbird|turbo-cache/.test(ref ?? '')), args[0]); + assert.ok(!('joined' in job.output), args[0]); + } +}); + +test('on a forge runner, a repo job joins nothing where the repo names no cache host or no overlay', () => { + for (const [args, env] of [ + [['repo', '--overlay', 'netbird'], {}], + [['repo', '--overlay', 'none'], CACHE_HOST], + [['repo'], CACHE_HOST], + ] as const) { + const job = runJob([...args], { env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...env }, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.ok(!job.calls.some((c) => c.tool === 'netbird'), args.join(' ')); + assert.deepEqual(Object.keys(job.env), ['DOCKER_CONFIG'], args.join(' ')); + } +}); + +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 }, + }); + assert.equal(job.status, 0, job.log); + assert.equal(job.output.joined, 'true'); + assert.ok(job.calls.some((c) => c.tool === 'netbird' && c.args[0] === 'status')); + assert.ok(!opReads(job).some((ref) => /turbo-cache/.test(ref ?? '')), 'a deploy job needs no cache'); +}); + +test('a repo job whose join fails goes on without the remote cache, and says so on the run', () => { + const job = runJob(['repo', '--overlay', 'netbird'], { + env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...CACHE_HOST }, + vault: { ...VAULT, ...OVERLAY_VAULT }, + netbirdFails: true, + }); + assert.equal(job.status, 0, job.log); + assert.match(job.log, /^::warning::.*overlay/m); + assert.ok(!('joined' in job.output)); + assert.equal(job.output['server-actions-key'], KEY); +}); + +test('a deploy job whose join fails fails', () => { + const job = runJob(['deploy', '--overlay', 'netbird'], { + env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER }, + vault: { ...DEPLOY_VAULT, ...OVERLAY_VAULT }, + netbirdFails: true, + }); + assert.equal(job.status, 1, job.log); + assert.match(job.log, /refused the setup key/); +}); + +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 }, + }); + assert.equal(job.status, 0, job.log); + assert.equal(job.output.joined, 'true'); + assert.ok(!job.calls.some((c) => c.tool === 'getent'), 'no wait for the cache host'); + assert.ok( + job.calls.filter((c) => c.tool === 'netbird' && c.args[0] === 'status').length >= 2, + 'the map is asked for', + ); + assert.ok(!opReads(job).some((ref) => /turbo-cache/.test(ref ?? '')), 'a deploy job reads no cache token'); +}); diff --git a/packages/cli-ci/src/commands/setup.ts b/packages/cli-ci/src/commands/setup.ts new file mode 100644 index 00000000..bd283ba9 --- /dev/null +++ b/packages/cli-ci/src/commands/setup.ts @@ -0,0 +1,93 @@ +// plx-ci setup : prepare a job of an app repo's pipeline in one +// step, after the checkout and mise (which brings plx-ci and the repo's tools) +// and before every other, so that each later step is one command. What it +// does depends on what the job is for, `repo` (the repo verbs, check to +// publish) or `deploy` (plx deploy), and on where it runs: a forge runner +// (RUNNER_ENVIRONMENT github-hosted) or a slot of the tenant's runner host, +// which is on the overlay already and whose repo slots carry their host's +// cache servers. In order: +// +// 1. 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 +// service account otherwise, and masks each secret in the log as it +// reads it, before anything else is printed: +// repo repo_/server-actions-key; on a forge runner of a repo +// that names a cache host (PLX_TURBO_CACHE_HOST, from its +// mise.toml) on `--overlay netbird`, also netbird/setup-key +// and turbo-cache/shared-token and turbo-cache/trusted-token +// deploy deploy-ssh/private key (as OpenSSH), 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 +// A key pasted into a one-line field gets its lines back, and each of +// them is masked as it is restored. +// 2. deploy: mint a token of the tenant's GitHub App that may read the +// operations repo (`--operations-repo`, default `operations`) and +// nothing else, and mask it. The App's key never leaves this process. +// Where GitHub refuses the App (401) or finds it not installed on the +// operations repo (404), the job fails in one line naming the App's +// client ID and the repo. +// 3. Say how the vault was read. +// 4. repo: log the job in to the forge's image registry with its own token +// (GITHUB_TOKEN as GITHUB_ACTOR), in a Docker config of the job's own +// under RUNNER_TEMP, which crane and buildx read; with +// `--private-packages`, to the forge's package registry too, in a +// user-level npmrc there. Each file is 0600 in a directory 0700. +// deploy: start an SSH agent on a socket under RUNNER_TEMP and add the +// deploy key. +// 5. On a forge runner, where step 1 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 +// key reaches the app hosts and not the cache host). A repo job that +// cannot join goes on without the remote cache and warns on the run; a +// deploy job fails. +// 6. Hand later steps what they need. As outputs of the step: +// repo server-actions-key, for the build and publish steps alone +// deploy operations-token, for the checkout of the operations repo +// both joined=true, where the job joined the overlay +// As variables of the job (GITHUB_ENV): DOCKER_CONFIG and, with private +// packages, NPM_CONFIG_USERCONFIG; PLX_TURBO_SHARED_TOKEN and +// PLX_TURBO_TRUSTED_TOKEN where step 1 read them; SSH_AUTH_SOCK. No +// secret of the vault is a variable of the job but the two cache tokens. +// +// Under --dry-run it reads and masks, calls no API, and writes and starts +// nothing. Exit code 1 where a read, the token or a deploy job's join fails. +// +// plx-ci setup repo --overlay netbird --private-packages +// plx-ci setup deploy --overlay netbird +import type { Command } from 'commander'; +import { Argument, Option } from 'commander'; +import { JOBS, type Job, setup } from '../core/setup.ts'; +import { OVERLAYS, type Overlay } from '../core/strategy.ts'; +import { contextOf } from '../program.ts'; + +export function register(program: Command): void { + program + .command('setup') + .description('prepare a job: read what it needs from the vault, log it in, and hand later steps what they need') + .addArgument(new Argument('', 'what the job is for: repo, the repo verbs; deploy, plx deploy').choices(JOBS)) + .addOption( + new Option( + '--overlay ', + 'how the job reaches the tenant’s hosts; netbird: a forge runner joins the overlay', + ) + .choices(OVERLAYS) + .default('none'), + ) + .option('--private-packages', 'the repo installs private packages from the forge’s package registry') + .option( + '--operations-repo ', + 'deploy: the tenant’s operations repo, in the owner’s organisation', + 'operations', + ) + .action( + async ( + job: Job, + opts: { overlay: Overlay; privatePackages?: boolean; operationsRepo: string }, + command: Command, + ) => { + await setup(contextOf(command), { job, ...opts }); + }, + ); +} diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts new file mode 100644 index 00000000..28d403aa --- /dev/null +++ b/packages/cli-ci/src/core/setup.ts @@ -0,0 +1,281 @@ +// What `plx-ci setup` does for a job (commands/setup.ts states the steps). +import { createSign } from 'node:crypto'; +import { appendFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { type Context, detailOf, orAbsent, type Plan, run, write } from '@plexus-ms/lib'; +import { need, ownerOf } from '../commands/shared.ts'; +import type { Overlay } from './strategy.ts'; +import { mask, vaultOf } from './vault.ts'; + +export const JOBS = ['repo', 'deploy'] as const; +export type Job = (typeof JOBS)[number]; + +export interface SetupOptions { + job: Job; + /** How the job reaches the tenant's hosts: `netbird`, over the overlay, which a forge runner joins. */ + overlay?: Overlay; + /** The repo installs private packages from the forge's package registry. */ + privatePackages?: boolean; + /** The tenant's operations repo, in the owner's organisation, whose inventory a deploy reads. */ + operationsRepo?: string; +} + +/** The forge's registries, which the job's own token logs in to. */ +const IMAGE_REGISTRY = 'ghcr.io'; +const PACKAGE_REGISTRY = 'npm.pkg.github.com'; +/** The NetBird client a forge runner installs to join the overlay. */ +const NETBIRD_VERSION = '0.82.0'; + +/** + * The tenant's cache host as the repo names it: its answer `turbo_cache_host`, + * which mise's environment hands every step of the job as + * PLX_TURBO_CACHE_HOST. Undefined where the repo names none. + */ +const cacheHostOf = (env: NodeJS.ProcessEnv): string | undefined => env.PLX_TURBO_CACHE_HOST?.trim() || undefined; + +export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.ProcessEnv = process.env): Promise { + const repository = need('GITHUB_REPOSITORY', env); + const owner = ownerOf(repository); + const repo = repository.split('/')[1] ?? repository; + const vaultName = `${owner}-ci`; + const temp = need('RUNNER_TEMP', env); + const vault = vaultOf(ctx, env); + const outputs: Record = {}; + const variables: Record = {}; + const plan: Plan = []; + // 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. + const cacheHost = cacheHostOf(env); + const overlay = + env.RUNNER_ENVIRONMENT === 'github-hosted' && + options.overlay === 'netbird' && + (options.job === 'deploy' || cacheHost !== undefined); + const setupKey = overlay ? await vault.read(`op://${vaultName}/netbird/setup-key`) : undefined; + + if (options.job === 'repo') { + outputs['server-actions-key'] = await vault.read(`op://${vaultName}/repo_${repo}/server-actions-key`); + if (overlay) { + variables.PLX_TURBO_SHARED_TOKEN = await vault.read(`op://${vaultName}/turbo-cache/shared-token`); + variables.PLX_TURBO_TRUSTED_TOKEN = await vault.read(`op://${vaultName}/turbo-cache/trusted-token`); + } + const token = need('GITHUB_TOKEN', env); + const docker = join(temp, 'docker'); + // The forge masks its token, not the token encoded. + const auth = Buffer.from(`${need('GITHUB_ACTOR', env)}:${token}`).toString('base64'); + mask(ctx, auth); + plan.push(...login(join(docker, 'config.json'), `${JSON.stringify({ auths: { [IMAGE_REGISTRY]: { auth } } })}\n`)); + variables.DOCKER_CONFIG = docker; + if (options.privatePackages) { + const npmrc = join(temp, 'npm', 'npmrc'); + plan.push(...login(npmrc, `//${PACKAGE_REGISTRY}/:_authToken=${token}\n`)); + variables.NPM_CONFIG_USERCONFIG = npmrc; + } + } else { + const sshKey = keyLines(ctx, await vault.read(`op://${vaultName}/deploy-ssh/private key?ssh-format=openssh`)); + const clientId = await vault.read(`op://${vaultName}/github-app/client-id`, { secret: false }); + const appKey = keyLines(ctx, await vault.read(`op://${vaultName}/github-app/private-key`)); + const operations = options.operationsRepo || 'operations'; + const token = await operationsToken(ctx, { + api: env.GITHUB_API_URL || 'https://api.github.com', + owner, + repo: operations, + clientId, + jwt: jwtOf(clientId, appKey), + }); + if (token) outputs['operations-token'] = token; + else ctx.say(`[dry-run] a token of the tenant’s App that may read ${owner}/${operations}`); + const socket = join(temp, 'ssh-agent.sock'); + plan.push( + run('ssh-agent', ['-a', socket]), + run('ssh-add', ['-'], { input: sshKey, env: { SSH_AUTH_SOCK: socket } }), + ); + variables.SSH_AUTH_SOCK = socket; + } + + ctx.say( + vault.access === 'connect' + ? `the vault ${vaultName}, through the runner’s Connect server` + : `the vault ${vaultName}, with the service account`, + ); + await ctx.apply(plan); + if (setupKey) { + try { + // The cache host is the repo job's to reach; a deploy job's key reaches the app hosts alone. + await joinOverlay(ctx, { + setupKey, + hostname: `ci-${need('GITHUB_RUN_ID', env)}-${options.job}`, + waitFor: options.job === 'repo' ? cacheHost : undefined, + }); + outputs.joined = 'true'; + } catch (error) { + // The cache spares work and is never a reason to fail: the verbs run without it, as turbow says. + if (options.job === 'deploy') throw error; + ctx.io.stdout.write( + `::warning::without the remote cache: the job did not join the overlay (${detailOf(error)})\n`, + ); + } + } + hand(ctx, 'the outputs of the step', () => need('GITHUB_OUTPUT', env), outputs); + hand(ctx, 'the environment of the job', () => need('GITHUB_ENV', env), variables); +} + +/** + * Join the tenant's overlay as a peer for the length of the job, as NetBird + * documents its client: from NetBird's Debian repository at a pinned version, + * up with the setup key in the environment (NB_SETUP_KEY), never on argv. The + * key's policy makes the peer ephemeral and lets it reach what the job needs. + * It counts as joined once the management server lists it as connected and, + * since names arrive with the network map some seconds later, once + * `waitFor` resolves, or without one once the map names any peer. + */ +async function joinOverlay( + ctx: Context, + { setupKey, hostname, waitFor }: { setupKey: string; hostname: string; waitFor?: string }, +): Promise { + const keyring = '/usr/share/keyrings/netbird-archive-keyring.gpg'; + const status = async () => await orAbsent(ctx.read('sudo', ['netbird', 'status'])); + const key = ctx.dryRun ? '' : await ctx.read('curl', ['-fsSL', 'https://pkgs.netbird.io/debian/public.key']); + await ctx.apply([ + run('sudo', ['gpg', '--dearmor', '-o', keyring], { input: key }), + run('sudo', ['tee', '/etc/apt/sources.list.d/netbird.list'], { + input: `deb [signed-by=${keyring}] https://pkgs.netbird.io/debian stable main\n`, + }), + run('sudo', ['apt-get', 'update', '-qq']), + run('sudo', ['apt-get', 'install', '-y', '-qq', `netbird=${NETBIRD_VERSION}`]), + run('sudo', ['--preserve-env=NB_SETUP_KEY', 'netbird', 'up', '--hostname', hostname], { + env: { NB_SETUP_KEY: setupKey }, + }), + ]); + if (ctx.dryRun) return; + await until('the management server listing the peer as connected', 30, async () => + /Management: Connected/.test((await status()) ?? ''), + ); + if (waitFor) + await until(`${waitFor} resolving on the overlay`, 60, async () => + Boolean(await orAbsent(ctx.read('getent', ['hosts', waitFor]))), + ); + else await until('the overlay’s network map', 60, async () => /Peers count: \d+\/[1-9]/.test((await status()) ?? '')); + ctx.say(`joined the overlay as ${hostname}`); +} + +/** Ask `ok` once a second, `seconds` times at most; an error naming `what` when it never answers yes. */ +async function until(what: string, seconds: number, ok: () => Promise): Promise { + for (let i = 0; i < seconds; i++) { + if (await ok()) return; + await new Promise((done) => setTimeout(done, 1000)); + } + throw new Error(`no ${what} within ${seconds} s`); +} + +/** Append `values` to a file the forge gives a step, one `name=value` line each; narrated by name alone. */ +function hand(ctx: Context, what: string, file: () => string, values: Record): void { + const names = Object.keys(values); + if (names.length === 0) return; + ctx.say(`${ctx.dryRun ? '[dry-run] ' : ''}${what}: ${names.join(', ')}`); + if (ctx.dryRun) return; + const path = file(); + for (const [name, value] of Object.entries(values)) { + if (value.includes('\n')) throw new Error(`${name} spans lines, and ${what} take one line each`); + appendFileSync(path, `${name}=${value}\n`); + } +} + +/** A login of the job's own: `content` at `path`, 0600 in a directory 0700, so that no other user reads it. */ +function login(path: string, content: string): Plan { + return [run('mkdir', ['-p', '-m', '700', dirname(path)]), write(path, content), run('chmod', ['600', path])]; +} + +/** + * 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. + */ +function keyLines(ctx: Context, key: string): string { + const k = key.trim(); + const pasted = /^(-----BEGIN [A-Z0-9 ]+-----) *(.*?) *(-----END [A-Z0-9 ]+-----)$/.exec(k); + const [, begin = '', body = '', end = ''] = pasted ?? []; + const lines = k.includes('\n') || !pasted ? `${k}\n` : `${[begin, ...body.split(/ +/), end].join('\n')}\n`; + mask(ctx, lines); + return lines; +} + +/** + * The JSON web token of the tenant's GitHub App, for its own API calls: RS256, + * issued by its client ID, backdated a minute for clock drift and valid for + * the ten minutes GitHub allows at most (GitHub's docs, "Generating a JSON Web + * Token (JWT) for a GitHub App"). Masked: it mints tokens while it lasts. + */ +function jwtOf(clientId: string, key: string): string { + const now = Math.floor(Date.now() / 1000); + const part = (o: object) => Buffer.from(JSON.stringify(o)).toString('base64url'); + const unsigned = `${part({ alg: 'RS256', typ: 'JWT' })}.${part({ iat: now - 60, exp: now + 540, iss: clientId })}`; + return `${unsigned}.${createSign('RSA-SHA256').update(unsigned).sign(key, 'base64url')}`; +} + +/** + * A token of the App's installation that may read `repo` and nothing else, + * masked as soon as it exists; undefined under --dry-run, which calls nothing. + * The App's key stays in this process: the job is handed the token alone, + * which expires within the hour. A call GitHub answers with an error fails in + * one line that names the App by its client ID and the repo, never the JWT. + */ +async function operationsToken( + ctx: Context, + { api, owner, repo, clientId, jwt }: { api: string; owner: string; repo: string; clientId: string; jwt: string }, +): Promise { + if (ctx.dryRun) return undefined; + mask(ctx, jwt); + const app = `the tenant’s GitHub App (client ID ${clientId})`; + const call = async (method: string, path: string, body?: unknown) => { + const out = await ctx.read('curl', ['-K', '-'], { input: curlConfig(method, `${api}${path}`, jwt, body) }); + const status = Number(out.slice(out.lastIndexOf('\n') + 1)); + const answer = parsed(out.slice(0, out.lastIndexOf('\n'))) as { id?: number; token?: string; message?: string }; + if (status >= 200 && status < 300) return answer; + const says = `GitHub answered ${status}${answer.message ? `, ${answer.message}` : ''}`.replace(/\s+/g, ' '); + if (status === 401) + throw new Error( + `GitHub refused ${app} for ${owner}/${repo}: its private key and client ID do not belong together, or the runner’s clock is off (${says})`, + ); + if (status === 404) throw new Error(`${app} is not installed on ${owner}/${repo}, or may not read it (${says})`); + throw new Error(`${method} ${path} for ${app} on ${owner}/${repo} failed (${says})`); + }; + const { id } = await call('GET', `/repos/${owner}/${repo}/installation`); + const { token } = await call('POST', `/app/installations/${id}/access_tokens`, { + repositories: [repo], + permissions: { contents: 'read' }, + }); + if (!token) throw new Error(`GitHub gave no token for ${owner}/${repo}`); + mask(ctx, token); + return token; +} + +/** An answer's JSON, or nothing where a proxy in between answered with a page of its own. */ +function parsed(body: string): unknown { + try { + return JSON.parse(body); + } catch { + return {}; + } +} + +/** + * A request for `curl -K -`: the credential on stdin, never on argv, where a + * process listing would show it. The answer's body, then a line with its HTTP + * status, which a caller reads to say what failed. + */ +function curlConfig(method: string, url: string, bearer: string, body?: unknown): string { + const lines = [ + `url = "${url}"`, + `request = "${method}"`, + 'silent', + 'show-error', + `header = "Authorization: Bearer ${bearer}"`, + 'header = "Accept: application/vnd.github+json"', + 'header = "X-GitHub-Api-Version: 2026-03-10"', + 'write-out = "\\n%{http_code}"', + ]; + if (body !== undefined) lines.push(`data = ${JSON.stringify(JSON.stringify(body))}`); + return `${lines.join('\n')}\n`; +} diff --git a/packages/cli-ci/src/core/vault.ts b/packages/cli-ci/src/core/vault.ts new file mode 100644 index 00000000..7560985d --- /dev/null +++ b/packages/cli-ci/src/core/vault.ts @@ -0,0 +1,54 @@ +// The one way a job reads the vault `-ci` (§ 3 PLX-Secrets): `op read`, +// through the runner's Connect server where the runner carries its address +// and token (OP_CONNECT_HOST and OP_CONNECT_TOKEN, which a slot of a runner +// host is handed), and with the service account otherwise +// (OP_SERVICE_ACCOUNT_TOKEN, which a workflow hands the step that runs +// `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. +// +// 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 +// no secret is not masked: the forge hides every occurrence of a masked +// string, and a short one, as the port of a relay, turns up inside hashes and +// hides them too. +import type { Context } from '@plexus-ms/lib'; + +export type VaultAccess = 'connect' | 'service account'; + +export interface Vault { + access: VaultAccess; + /** The value at `ref`, an `op://` reference, without the newline `op` ends it with; masked unless `secret` is false. */ + read(ref: string, options?: { secret?: boolean }): Promise; +} + +const CONNECT = ['OP_CONNECT_HOST', 'OP_CONNECT_TOKEN'] as const; + +/** + * Hide `value` in the job's log: the forge's `::add-mask::` command on stdout, + * once per line, since a command is one line and a key in the vault is many. + */ +export function mask(ctx: Context, value: string): void { + for (const line of value.split('\n').map((l) => l.trim())) if (line) ctx.io.stdout.write(`::add-mask::${line}\n`); +} + +/** The vault as this runner reaches it; an error naming both ways where it reaches it neither way. */ +export function vaultOf(ctx: Context, env: NodeJS.ProcessEnv = process.env): Vault { + const connect = CONNECT.every((name) => env[name]); + if (!connect && !env.OP_SERVICE_ACCOUNT_TOKEN) + throw new Error( + 'the job cannot read the vault: the runner carries no Connect server (OP_CONNECT_HOST and OP_CONNECT_TOKEN), and the step was handed no OP_SERVICE_ACCOUNT_TOKEN', + ); + const opEnv = { ...env }; + if (connect) delete opEnv.OP_SERVICE_ACCOUNT_TOKEN; + else for (const name of CONNECT) delete opEnv[name]; + return { + access: connect ? 'connect' : 'service account', + read: async (ref, { secret = true } = {}) => { + const value = (await ctx.read('op', ['read', ref], { env: opEnv })).replace(/\n$/, ''); + if (secret) mask(ctx, value); + return value; + }, + }; +} diff --git a/packages/cli-ci/src/program.test.ts b/packages/cli-ci/src/program.test.ts index 272e187b..3e544fa6 100644 --- a/packages/cli-ci/src/program.test.ts +++ b/packages/cli-ci/src/program.test.ts @@ -35,7 +35,7 @@ test('help lists the global options', () => { test('the universal commands take --strategy, and hybrid holds the instances’ three', () => { const program = buildProgram(); const names = program.commands.map((c) => c.name()); - assert.deepEqual(names, ['plan', 'publish', 'display-versions', 'tag-display-version', 'hybrid']); + assert.deepEqual(names, ['setup', 'plan', 'publish', 'display-versions', 'tag-display-version', 'hybrid']); for (const name of ['plan']) { const command = program.commands.find((c) => c.name() === name); assert.ok( diff --git a/packages/cli-ci/src/testing/job.ts b/packages/cli-ci/src/testing/job.ts new file mode 100644 index 00000000..84887037 --- /dev/null +++ b/packages/cli-ci/src/testing/job.ts @@ -0,0 +1,188 @@ +// A job of the forge for the tests of `plx-ci setup`, run as a process: plx-ci +// from source, with the files the forge gives a step (GITHUB_OUTPUT, +// GITHUB_ENV, RUNNER_TEMP) in a directory of the test's own, and fakes first +// on the PATH for every tool the command may start. Each fake records its call +// as one JSON line: the tool, its arguments, what it was fed, and which of the +// vault's and the overlay's variables it saw. Not shipped (excluded in +// tsconfig). +// +// op `op read ` answers from `vault`, else fails as op does +// curl the forge's API, as curl answers with the config's `fail-with-body` +// or `write-out`: a repository's installation, and a token for it, +// or for every call the status `apiStatus`; any other download, a key +// sudo runs the rest of its arguments, its own options dropped +// netbird `up` and `down` succeed unless `netbirdFails`; `status` is connected +// getent every name resolves +// ssh-agent, ssh-add, gpg, tee, apt-get succeed +import { spawnSync } from 'node:child_process'; +import { + chmodSync, + closeSync, + existsSync, + mkdirSync, + mkdtempSync, + openSync, + readFileSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const BIN = join(import.meta.dirname, '..', 'bin.ts'); + +/** The variables a fake reports having seen, by name; each a value or absent. */ +const SEEN = ['OP_CONNECT_HOST', 'OP_CONNECT_TOKEN', 'OP_SERVICE_ACCOUNT_TOKEN', 'NB_SETUP_KEY', 'SSH_AUTH_SOCK']; + +const FAKE = `#!/usr/bin/env node +const { appendFileSync, readFileSync } = require('node:fs'); +const { basename } = require('node:path'); +const tool = basename(process.argv[1]); +const args = process.argv.slice(2); +const input = ['ssh-add', 'gpg', 'tee'].includes(tool) || args.includes('-K') ? readFileSync(0, 'utf8') : undefined; +const seen = Object.fromEntries(${JSON.stringify(SEEN)}.filter((k) => process.env[k] !== undefined).map((k) => [k, process.env[k]])); +appendFileSync(process.env.FAKE_LOG, JSON.stringify({ tool, args, input, seen }) + '\\n'); +const fail = (message) => { process.stderr.write(message + '\\n'); process.exit(1); }; +switch (tool) { + case 'op': { + const vault = JSON.parse(readFileSync(process.env.FAKE_VAULT, 'utf8')); + const ref = args[1]; + if (args[0] !== 'read' || !(ref in vault)) fail('[ERROR] could not read secret ' + ref); + process.stdout.write(vault[ref] + '\\n'); + break; + } + case 'curl': { + if (!input) { + process.stdout.write('-----BEGIN PGP PUBLIC KEY BLOCK-----\\nfake\\n-----END PGP PUBLIC KEY BLOCK-----\\n'); + break; + } + const url = /^url = "(.*)"$/m.exec(input)[1]; + const failed = process.env.FAKE_API_STATUS; + const [status, body] = failed + ? [Number(failed), { message: failed === '401' ? 'A JSON web token could not be decoded' : 'Not Found', status: failed }] + : url.endsWith('/installation') + ? [200, { id: 42 }] + : url.endsWith('/app/installations/42/access_tokens') + ? [201, { token: 'ghs_operations', expires_at: '2026-12-02T05:00:00Z' }] + : [404, { message: 'Not Found', status: '404' }]; + process.stdout.write(JSON.stringify(body)); + if (status >= 400 && /^fail-with-body$/m.test(input)) { + process.stderr.write('curl: (22) The requested URL returned error: ' + status + '\\n'); + process.exit(22); + } + const writeOut = /^write-out = "(.*)"$/m.exec(input); + if (writeOut) process.stdout.write(writeOut[1].replaceAll('\\\\n', '\\n').replaceAll('%{http_code}', String(status))); + break; + } + case 'sudo': { + const rest = args.slice(args.findIndex((a) => !a.startsWith('-'))); + const run = require('node:child_process').spawnSync(rest[0], rest.slice(1), { stdio: 'inherit' }); + process.exit(run.status ?? 1); + } + case 'netbird': + if (process.env.FAKE_NETBIRD_FAILS && args[0] === 'up') fail('netbird: the management server refused the setup key'); + if (args[0] === 'status') process.stdout.write('Management: Connected\\nSignal: Connected\\nPeers count: 0/3 Connected\\n'); + break; + case 'getent': + process.stdout.write('100.64.0.9 ' + args[1] + '\\n'); + break; +} +`; + +const TOOLS = ['op', 'curl', 'sudo', 'netbird', 'getent', 'ssh-agent', 'ssh-add', 'gpg', 'tee', 'apt-get']; + +/** One call a fake recorded. */ +export interface Call { + tool: string; + args: string[]; + input?: string; + seen: Record; +} + +export interface Job { + status: number | null; + /** stdout and stderr together, in the order they were written. */ + log: string; + /** What the step handed later steps, by name. */ + output: Record; + /** What the step put into the job's environment, by name. */ + env: Record; + calls: Call[]; + /** The job's RUNNER_TEMP. */ + temp: string; +} + +/** The `name=value` lines of a file the forge gives a step, or none where the step wrote nothing. */ +function handed(path: string): Record { + if (!existsSync(path)) return {}; + return Object.fromEntries( + readFileSync(path, 'utf8') + .split('\n') + .filter(Boolean) + .map((line) => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)]), + ); +} + +/** + * `plx-ci setup ` in a job of the repository acme/web, run 41, with + * `env` beside the forge's own variables and `vault` as what `op` can read. + */ +export function runJob( + args: string[], + options: { + env?: Record; + vault?: Record; + netbirdFails?: boolean; + apiStatus?: number; + } = {}, +): Job { + const dir = mkdtempSync(join(tmpdir(), 'plx-ci-setup-')); + const bin = join(dir, 'bin'); + const temp = join(dir, 'temp'); + mkdirSync(bin); + mkdirSync(temp); + for (const tool of TOOLS) { + writeFileSync(join(bin, tool), FAKE); + chmodSync(join(bin, tool), 0o755); + } + const vault = join(dir, 'vault.json'); + writeFileSync(vault, JSON.stringify(options.vault ?? {})); + const logPath = join(dir, 'log'); + const fd = openSync(logPath, 'w'); + const run = spawnSync(process.execPath, [BIN, 'setup', ...args], { + stdio: ['ignore', fd, fd], + timeout: 60_000, + env: { + PATH: `${bin}:${process.env.PATH}`, + HOME: dir, + GITHUB_ACTIONS: 'true', + GITHUB_REPOSITORY: 'acme/web', + GITHUB_REPOSITORY_OWNER: 'acme', + GITHUB_ACTOR: 'octocat', + GITHUB_RUN_ID: '41', + GITHUB_TOKEN: 'ghs_job', + GITHUB_OUTPUT: join(dir, 'output'), + GITHUB_ENV: join(dir, 'env'), + RUNNER_TEMP: temp, + FAKE_LOG: join(dir, 'calls'), + FAKE_VAULT: vault, + ...(options.netbirdFails ? { FAKE_NETBIRD_FAILS: '1' } : {}), + ...(options.apiStatus ? { FAKE_API_STATUS: String(options.apiStatus) } : {}), + ...options.env, + }, + }); + closeSync(fd); + const calls = existsSync(join(dir, 'calls')) + ? readFileSync(join(dir, 'calls'), 'utf8') + .split('\n') + .filter(Boolean) + .map((line) => JSON.parse(line) as Call) + : []; + return { + status: run.status, + log: readFileSync(logPath, 'utf8'), + output: handed(join(dir, 'output')), + env: handed(join(dir, 'env')), + calls, + temp, + }; +} diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index ebaeaf1b..ce909bb6 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -67,11 +67,17 @@ test('the answers of a plain app repo are the questions’ defaults', async () = private_packages_scope: '', ci_strategy: 'github', ci_overlay: 'none', + ci_service_account: true, display_versions: false, postgres: '', }); }); +test('an app repo is asked whether its jobs are handed the service account token, a package repo is not', async () => { + assert.equal((await render({ ci_service_account: false })).answers.ci_service_account, false); + assert.ok(!('ci_service_account' in (await render({ publishes_packages: true })).answers)); +}); + test('a package repo is asked where it publishes', async () => { const result = await render({ publishes_packages: true }); assert.equal(result.answers.package_registry, 'npm'); diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index 59438d7f..5edecfb5 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -48,6 +48,12 @@ questions: default: none when: "{{ not publishes_packages }}" + ci_service_account: + type: bool + help: "Do the workflows hand their jobs the service account token of the vault -ci (§ 8 PLX-Delivery)? No for a repo whose jobs all run on slots of a runner host, which read the vault through its Connect server; the workflows then do not mention the token" + default: true + when: "{{ not publishes_packages }}" + alerts_email: type: str help: "Hybrid strategy: the address mailed when an instance misses its boot and is kept (empty: no mail); a fact, so an answer here and never a vault item"