From ac8074a7c36ad8fe1afaefa87f8016f35bc91444 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:07:24 +0100 Subject: [PATCH 01/15] test: repo-turbo asks an app repo ci_service_account (PLX-227) Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/repoTurbo.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index 925e57b7..cdd0e5d6 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'); From 7c507f99acc7a9ba173e8003d701f127cc233ed1 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:09:00 +0100 Subject: [PATCH 02/15] repo-turbo: an app repo answers ci_service_account (PLX-227) Whether the workflows hand their jobs the service account token of the CI vault; the workflows that act on it are rendered elsewhere. Co-Authored-By: Claude Opus 5.5 --- templates/repo-turbo/template.yml | 6 ++++++ 1 file changed, 6 insertions(+) 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" From 8d9fec4620e2000f18af86b7fd2bfd8189f6c74f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:09:24 +0100 Subject: [PATCH 03/15] test: plx-ci setup reads the vault through Connect where the runner has it, else with the service account (PLX-227) Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.test.ts | 65 ++++++++ packages/cli-ci/src/program.test.ts | 2 +- packages/cli-ci/src/testing/job.ts | 165 +++++++++++++++++++++ 3 files changed, 231 insertions(+), 1 deletion(-) create mode 100644 packages/cli-ci/src/commands/setup.test.ts create mode 100644 packages/cli-ci/src/testing/job.ts 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..2724b2bc --- /dev/null +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -0,0 +1,65 @@ +// 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 { 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/); +}); 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..5420108d --- /dev/null +++ b/packages/cli-ci/src/testing/job.ts @@ -0,0 +1,165 @@ +// 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: a repository's installation, and a token for it +// 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', 'curl', 'gpg', 'tee'].includes(tool) ? 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': { + const url = /^url = "(.*)"$/m.exec(input)[1]; + if (url.endsWith('/installation')) process.stdout.write(JSON.stringify({ id: 42 })); + else if (url.endsWith('/app/installations/42/access_tokens')) + process.stdout.write(JSON.stringify({ token: 'ghs_operations', expires_at: '2026-12-02T05:00:00Z' })); + else fail('curl: (22) The requested URL returned error: 404'); + break; + } + case 'sudo': { + const rest = args.filter((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 } = {}, +): 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.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, + }; +} From 7659d391459df9924c00346e9aee639381802fda Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:10:27 +0100 Subject: [PATCH 04/15] plx-ci setup: every vault read of a job through one function, Connect before the service account (PLX-227) Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/index.ts | 3 ++- packages/cli-ci/src/commands/setup.ts | 19 ++++++++++++++ packages/cli-ci/src/core/setup.ts | 26 +++++++++++++++++++ packages/cli-ci/src/core/vault.ts | 36 +++++++++++++++++++++++++++ 4 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 packages/cli-ci/src/commands/setup.ts create mode 100644 packages/cli-ci/src/core/setup.ts create mode 100644 packages/cli-ci/src/core/vault.ts diff --git a/packages/cli-ci/src/commands/index.ts b/packages/cli-ci/src/commands/index.ts index b79524b9..7f253369 100644 --- a/packages/cli-ci/src/commands/index.ts +++ b/packages/cli-ci/src/commands/index.ts @@ -9,5 +9,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.ts b/packages/cli-ci/src/commands/setup.ts new file mode 100644 index 00000000..5d530b04 --- /dev/null +++ b/packages/cli-ci/src/commands/setup.ts @@ -0,0 +1,19 @@ +// plx-ci setup : prepare a job of an app repo's pipeline, once, +// after the checkout and mise, so that every later step is one command. +// +// plx-ci setup repo +// plx-ci setup deploy +import type { Command } from 'commander'; +import { Argument } from 'commander'; +import { JOBS, type Job, setup } from '../core/setup.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)) + .action(async (job: Job, _opts: Record, command: Command) => { + await setup(contextOf(command), { job }); + }); +} diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts new file mode 100644 index 00000000..d0ed0876 --- /dev/null +++ b/packages/cli-ci/src/core/setup.ts @@ -0,0 +1,26 @@ +// What `plx-ci setup` does for a job (commands/setup.ts states the steps). +import type { Context } from '@plexus-ms/lib'; +import { need, ownerOf } from '../commands/shared.ts'; +import { vaultOf } from './vault.ts'; + +export const JOBS = ['repo', 'deploy'] as const; +export type Job = (typeof JOBS)[number]; + +export interface SetupOptions { + job: Job; +} + +export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.ProcessEnv = process.env): Promise { + const repository = need('GITHUB_REPOSITORY', env); + const vaultName = `${ownerOf(repository)}-ci`; + const vault = vaultOf(ctx, env); + if (options.job === 'repo') { + const repo = repository.split('/')[1] ?? repository; + await vault.read(`op://${vaultName}/repo_${repo}/server-actions-key`); + } + ctx.say( + vault.access === 'connect' + ? `the vault ${vaultName}, through the runner’s Connect server` + : `the vault ${vaultName}, with the service account`, + ); +} diff --git a/packages/cli-ci/src/core/vault.ts b/packages/cli-ci/src/core/vault.ts new file mode 100644 index 00000000..4fd1e703 --- /dev/null +++ b/packages/cli-ci/src/core/vault.ts @@ -0,0 +1,36 @@ +// 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. +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. */ + read(ref: string): Promise; +} + +const CONNECT = ['OP_CONNECT_HOST', 'OP_CONNECT_TOKEN'] as const; + +/** The vault as this runner reaches it; a usage 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) => (await ctx.read('op', ['read', ref], { env: opEnv })).replace(/\n$/, ''), + }; +} From 7fa12407d41ab981391446b75c43d61a7931ccf6 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:10:53 +0100 Subject: [PATCH 05/15] test: what plx-ci setup hands a repo job, and that the server-actions key is in no variable of it (PLX-227) Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.test.ts | 49 ++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts index 2724b2bc..d69b93f8 100644 --- a/packages/cli-ci/src/commands/setup.test.ts +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -2,6 +2,8 @@ // 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 { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; import { test } from 'node:test'; import { runJob } from '../testing/job.ts'; @@ -63,3 +65,50 @@ test('an item the vault does not hold fails the job, naming the reference', () = 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.deepEqual(masksFirst(job.log), [`::add-mask::${KEY}`]); + 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')); + assert.deepEqual(config, { auths: { 'ghcr.io': { auth: Buffer.from('octocat:ghs_job').toString('base64') } } }); +}); + +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, 'npmrc')); + assert.equal(readFileSync(join(job.temp, 'npmrc'), 'utf8'), '//npm.pkg.github.com/:_authToken=ghs_job\n'); +}); + +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.deepEqual(masksFirst(job.log), [`::add-mask::${KEY}`]); + assert.deepEqual([job.output, job.env], [{}, {}]); + assert.deepEqual(readdirSync(job.temp), []); +}); From 6c59fecbcd13fcf0fdceb72b096ecd0ff7620ef5 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:11:37 +0100 Subject: [PATCH 06/15] plx-ci setup repo: the server-actions key as a masked step output, and the logins to the forge's registries (PLX-227) Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.ts | 5 +-- packages/cli-ci/src/core/setup.ts | 49 +++++++++++++++++++++++++-- packages/cli-ci/src/core/vault.ts | 26 +++++++++++--- 3 files changed, 71 insertions(+), 9 deletions(-) diff --git a/packages/cli-ci/src/commands/setup.ts b/packages/cli-ci/src/commands/setup.ts index 5d530b04..c199a679 100644 --- a/packages/cli-ci/src/commands/setup.ts +++ b/packages/cli-ci/src/commands/setup.ts @@ -13,7 +13,8 @@ export function register(program: Command): void { .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)) - .action(async (job: Job, _opts: Record, command: Command) => { - await setup(contextOf(command), { job }); + .option('--private-packages', 'the repo installs private packages from the forge’s package registry') + .action(async (job: Job, opts: { privatePackages?: boolean }, command: Command) => { + await setup(contextOf(command), { job, privatePackages: opts.privatePackages }); }); } diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts index d0ed0876..b0cea98e 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -1,5 +1,7 @@ // What `plx-ci setup` does for a job (commands/setup.ts states the steps). -import type { Context } from '@plexus-ms/lib'; +import { appendFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { type Context, type Plan, run, write } from '@plexus-ms/lib'; import { need, ownerOf } from '../commands/shared.ts'; import { vaultOf } from './vault.ts'; @@ -8,19 +10,60 @@ export type Job = (typeof JOBS)[number]; export interface SetupOptions { job: Job; + /** The repo installs private packages from the forge's package registry. */ + privatePackages?: boolean; } +/** 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'; + export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.ProcessEnv = process.env): Promise { const repository = need('GITHUB_REPOSITORY', env); + const repo = repository.split('/')[1] ?? repository; const vaultName = `${ownerOf(repository)}-ci`; + const temp = need('RUNNER_TEMP', env); const vault = vaultOf(ctx, env); + const outputs: Record = {}; + const variables: Record = {}; + const plan: Plan = []; + if (options.job === 'repo') { - const repo = repository.split('/')[1] ?? repository; - await vault.read(`op://${vaultName}/repo_${repo}/server-actions-key`); + outputs['server-actions-key'] = await vault.read(`op://${vaultName}/repo_${repo}/server-actions-key`); + const token = need('GITHUB_TOKEN', env); + const docker = join(temp, 'docker'); + const auth = Buffer.from(`${need('GITHUB_ACTOR', env)}:${token}`).toString('base64'); + plan.push( + run('mkdir', ['-p', docker]), + write(join(docker, 'config.json'), `${JSON.stringify({ auths: { [IMAGE_REGISTRY]: { auth } } })}\n`), + ); + variables.DOCKER_CONFIG = docker; + if (options.privatePackages) { + const npmrc = join(temp, 'npmrc'); + plan.push(write(npmrc, `//${PACKAGE_REGISTRY}/:_authToken=${token}\n`)); + variables.NPM_CONFIG_USERCONFIG = npmrc; + } } + 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); + hand(ctx, 'the outputs of the step', () => need('GITHUB_OUTPUT', env), outputs); + hand(ctx, 'the environment of the job', () => need('GITHUB_ENV', env), variables); +} + +/** 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`); + } } diff --git a/packages/cli-ci/src/core/vault.ts b/packages/cli-ci/src/core/vault.ts index 4fd1e703..7560985d 100644 --- a/packages/cli-ci/src/core/vault.ts +++ b/packages/cli-ci/src/core/vault.ts @@ -7,19 +7,33 @@ // 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. */ - read(ref: string): Promise; + /** 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; -/** The vault as this runner reaches it; a usage error naming both ways where it reaches it neither way. */ +/** + * 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) @@ -31,6 +45,10 @@ export function vaultOf(ctx: Context, env: NodeJS.ProcessEnv = process.env): Vau else for (const name of CONNECT) delete opEnv[name]; return { access: connect ? 'connect' : 'service account', - read: async (ref) => (await ctx.read('op', ['read', ref], { env: opEnv })).replace(/\n$/, ''), + read: async (ref, { secret = true } = {}) => { + const value = (await ctx.read('op', ['read', ref], { env: opEnv })).replace(/\n$/, ''); + if (secret) mask(ctx, value); + return value; + }, }; } From b0261dcd4c78792f69666ffb852ce050344faaf8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:12:15 +0100 Subject: [PATCH 07/15] test: what plx-ci setup hands a deploy job: the deploy key in an agent, a token of the App for the operations repo (PLX-227) Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.test.ts | 95 ++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts index d69b93f8..1d5ce038 100644 --- a/packages/cli-ci/src/commands/setup.test.ts +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -2,6 +2,7 @@ // 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 } from 'node:fs'; import { join } from 'node:path'; import { test } from 'node:test'; @@ -112,3 +113,97 @@ test('under --dry-run the vault is read and masked, and nothing is handed or wri 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`); +}); + +/** 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'); + } +}); + +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); +}); From 00a6f187be7f8d1a781986bdc7b7641cbf255a61 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:13:02 +0100 Subject: [PATCH 08/15] plx-ci setup deploy: the deploy key in an SSH agent, and a token of the App that may read the operations repo (PLX-227) The App's key stays in plx-ci: the job is handed a token for the one repo and contents: read, masked, in place of an action that would need the key as a step output. Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.ts | 13 +++- packages/cli-ci/src/core/setup.ts | 93 ++++++++++++++++++++++++++- 2 files changed, 103 insertions(+), 3 deletions(-) diff --git a/packages/cli-ci/src/commands/setup.ts b/packages/cli-ci/src/commands/setup.ts index c199a679..7606eb34 100644 --- a/packages/cli-ci/src/commands/setup.ts +++ b/packages/cli-ci/src/commands/setup.ts @@ -14,7 +14,16 @@ export function register(program: Command): void { .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)) .option('--private-packages', 'the repo installs private packages from the forge’s package registry') - .action(async (job: Job, opts: { privatePackages?: boolean }, command: Command) => { - await setup(contextOf(command), { job, privatePackages: opts.privatePackages }); + .option( + '--operations-repo ', + 'deploy: the tenant’s operations repo, in the owner’s organisation', + 'operations', + ) + .action(async (job: Job, opts: { privatePackages?: boolean; operationsRepo: string }, command: Command) => { + await setup(contextOf(command), { + job, + privatePackages: opts.privatePackages, + operationsRepo: opts.operationsRepo, + }); }); } diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts index b0cea98e..5b366164 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -1,9 +1,10 @@ // 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 { join } from 'node:path'; import { type Context, type Plan, run, write } from '@plexus-ms/lib'; import { need, ownerOf } from '../commands/shared.ts'; -import { vaultOf } from './vault.ts'; +import { mask, vaultOf } from './vault.ts'; export const JOBS = ['repo', 'deploy'] as const; export type Job = (typeof JOBS)[number]; @@ -12,6 +13,8 @@ export interface SetupOptions { job: Job; /** 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. */ @@ -43,6 +46,25 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro plan.push(write(npmrc, `//${PACKAGE_REGISTRY}/:_authToken=${token}\n`)); variables.NPM_CONFIG_USERCONFIG = npmrc; } + } else { + const sshKey = keyLines(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(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: ownerOf(repository), + repo: operations, + 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 ${ownerOf(repository)}/${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( @@ -67,3 +89,72 @@ function hand(ctx: Context, what: string, file: () => string, values: Record 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 mints none. + * The App's key stays in this process: the job is handed the token alone, + * which expires within the hour. + */ +async function operationsToken( + ctx: Context, + { api, owner, repo, jwt }: { api: string; owner: string; repo: string; jwt: string }, +): Promise { + mask(ctx, jwt); + const call = async (method: string, path: string, body?: unknown) => { + const out = await ctx.read('curl', ['-K', '-'], { input: curlConfig(method, `${api}${path}`, jwt, body) }); + return JSON.parse(out) as { id?: number; token?: string }; + }; + const { id } = await call('GET', `/repos/${owner}/${repo}/installation`); + if (!id) throw new Error(`the tenant’s App is not installed on ${owner}/${repo}`); + if (ctx.dryRun) return undefined; + 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; +} + +/** A request for `curl -K -`: the credential on stdin, never on argv, where a process listing would show it. */ +function curlConfig(method: string, url: string, bearer: string, body?: unknown): string { + const lines = [ + `url = "${url}"`, + `request = "${method}"`, + 'fail-with-body', + 'silent', + 'show-error', + `header = "Authorization: Bearer ${bearer}"`, + 'header = "Accept: application/vnd.github+json"', + 'header = "X-GitHub-Api-Version: 2026-03-10"', + ]; + if (body !== undefined) lines.push(`data = ${JSON.stringify(JSON.stringify(body))}`); + return `${lines.join('\n')}\n`; +} From b484c455baca9586212e55bac10af6129ac042ba Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:13:48 +0100 Subject: [PATCH 09/15] test: plx-ci setup joins the overlay on a forge runner and never on a slot (PLX-227) Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.test.ts | 97 ++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts index 1d5ce038..897f3ffa 100644 --- a/packages/cli-ci/src/commands/setup.test.ts +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -207,3 +207,100 @@ test('the App’s client ID is read as no secret and is not masked, as the port 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'], 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/); +}); From 567db14bfc10142f304512eeca018f21d8ac7698 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:15:43 +0100 Subject: [PATCH 10/15] plx-ci setup: a forge runner joins the overlay for the cache host or the app hosts, and a repo job gets the caches' tokens (PLX-227) The command's header states its steps in order. The fakes of the tests answer a plain download and keep the options of the command sudo runs. Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.ts | 83 ++++++++++++++++++++---- packages/cli-ci/src/core/setup.ts | 93 +++++++++++++++++++++++++-- packages/cli-ci/src/testing/job.ts | 11 +++- 3 files changed, 168 insertions(+), 19 deletions(-) diff --git a/packages/cli-ci/src/commands/setup.ts b/packages/cli-ci/src/commands/setup.ts index 7606eb34..aedd73d2 100644 --- a/packages/cli-ci/src/commands/setup.ts +++ b/packages/cli-ci/src/commands/setup.ts @@ -1,11 +1,60 @@ -// plx-ci setup : prepare a job of an app repo's pipeline, once, -// after the checkout and mise, so that every later step is one command. +// 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: // -// plx-ci setup repo -// plx-ci setup deploy +// 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 +// 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. +// 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. +// deploy: start an SSH agent on a socket under RUNNER_TEMP and add the +// deploy key, its lines restored where it was pasted into a one-line +// field. +// 5. On a forge runner, where step 1 read a setup key: join the overlay as +// an ephemeral peer, and wait until the cache host resolves (repo) or +// the network map names a peer (deploy). 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, mints no token, 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 } 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 { @@ -13,17 +62,27 @@ export function register(program: Command): void { .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: { privatePackages?: boolean; operationsRepo: string }, command: Command) => { - await setup(contextOf(command), { - job, - privatePackages: opts.privatePackages, - operationsRepo: opts.operationsRepo, - }); - }); + .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 index 5b366164..29112085 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -2,8 +2,9 @@ import { createSign } from 'node:crypto'; import { appendFileSync } from 'node:fs'; import { join } from 'node:path'; -import { type Context, type Plan, run, write } from '@plexus-ms/lib'; +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; @@ -11,6 +12,8 @@ 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. */ @@ -20,19 +23,41 @@ export interface SetupOptions { /** 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 = `${ownerOf(repository)}-ci`; + 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'); const auth = Buffer.from(`${need('GITHUB_ACTOR', env)}:${token}`).toString('base64'); @@ -53,12 +78,12 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro const operations = options.operationsRepo || 'operations'; const token = await operationsToken(ctx, { api: env.GITHUB_API_URL || 'https://api.github.com', - owner: ownerOf(repository), + owner, repo: operations, 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 ${ownerOf(repository)}/${operations}`); + 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]), @@ -73,10 +98,70 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro : `the vault ${vaultName}, with the service account`, ); await ctx.apply(plan); + if (setupKey) { + try { + await joinOverlay(ctx, { setupKey, hostname: `ci-${need('GITHUB_RUN_ID', env)}`, waitFor: cacheHost }); + 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); diff --git a/packages/cli-ci/src/testing/job.ts b/packages/cli-ci/src/testing/job.ts index 5420108d..4952be65 100644 --- a/packages/cli-ci/src/testing/job.ts +++ b/packages/cli-ci/src/testing/job.ts @@ -7,7 +7,8 @@ // tsconfig). // // op `op read ` answers from `vault`, else fails as op does -// curl the forge's API: a repository's installation, and a token for it +// curl the forge's API: a repository's installation, and a token for it; +// 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 @@ -36,7 +37,7 @@ 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', 'curl', 'gpg', 'tee'].includes(tool) ? readFileSync(0, 'utf8') : undefined; +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); }; @@ -49,6 +50,10 @@ switch (tool) { 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]; if (url.endsWith('/installation')) process.stdout.write(JSON.stringify({ id: 42 })); else if (url.endsWith('/app/installations/42/access_tokens')) @@ -57,7 +62,7 @@ switch (tool) { break; } case 'sudo': { - const rest = args.filter((a) => !a.startsWith('-')); + 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); } From bc0760cb94c25a783c9f676d01fb24be864d4fa1 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:16:01 +0100 Subject: [PATCH 11/15] plx-ci: the setup of a job is the first of its commands (PLX-227) Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/package.json | 2 +- packages/cli-ci/src/commands/index.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) 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 7f253369..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'; From 9a4b6027a5fea31f3fcb1381d562d86f17a72231 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:17:56 +0100 Subject: [PATCH 12/15] test: the job's token, encoded in the Docker config, is masked (PLX-227) Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts index 897f3ffa..a6ebd51e 100644 --- a/packages/cli-ci/src/commands/setup.test.ts +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -96,7 +96,9 @@ test('a repo job is logged in to the forge’s image registry with its own token 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')); - assert.deepEqual(config, { auths: { 'ghcr.io': { auth: Buffer.from('octocat:ghs_job').toString('base64') } } }); + 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', () => { From 1935dd994fa7a788c8b9fe49f0297ea9ff5a3402 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:18:10 +0100 Subject: [PATCH 13/15] plx-ci setup: the Docker config's credential is masked (PLX-227) Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.test.ts | 4 ++-- packages/cli-ci/src/core/setup.ts | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts index a6ebd51e..a870acec 100644 --- a/packages/cli-ci/src/commands/setup.test.ts +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -80,7 +80,7 @@ test('a repo job hands the server-actions key to later steps as an output, maske const job = runJob(['repo'], { env: CONNECT, vault: VAULT }); assert.equal(job.status, 0, job.log); assert.equal(job.output['server-actions-key'], KEY); - assert.deepEqual(masksFirst(job.log), [`::add-mask::${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'); }); @@ -111,7 +111,7 @@ test('a repo job that installs private packages is logged in to the forge’s pa 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.deepEqual(masksFirst(job.log), [`::add-mask::${KEY}`]); + assert.ok(masksFirst(job.log).includes(`::add-mask::${KEY}`), job.log); assert.deepEqual([job.output, job.env], [{}, {}]); assert.deepEqual(readdirSync(job.temp), []); }); diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts index 29112085..20838276 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -60,7 +60,9 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro } 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( run('mkdir', ['-p', docker]), write(join(docker, 'config.json'), `${JSON.stringify({ auths: { [IMAGE_REGISTRY]: { auth } } })}\n`), From 2dd77399e831f17473faa60680c5ef39d49327b4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:43:18 +0100 Subject: [PATCH 14/15] Test what the review of setup asks: the cache host, -v, the App's errors, dry-run, modes, names (PLX-227) - A deploy job on a forge runner waits for the network map even where the repo names a cache host, and reads no cache token. - With -v, the lines of a key pasted into a one-line field are each masked before they are shown. - A 404 and a 401 of the App's calls each end in one line naming the App's client ID and the operations repo, told apart, with no JWT; the fake curl answers as curl does under fail-with-body or write-out. - Under --dry-run a deploy job calls nothing but the vault. - The Docker config and the npmrc are 0600 in directories 0700; the npmrc moves to a directory of its own. - The repo job joins as ci--repo. Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.test.ts | 92 ++++++++++++++++++++-- packages/cli-ci/src/testing/job.ts | 32 ++++++-- 2 files changed, 112 insertions(+), 12 deletions(-) diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts index a870acec..f3c17f3b 100644 --- a/packages/cli-ci/src/commands/setup.test.ts +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -3,8 +3,8 @@ // the PATH (testing/job.ts). import assert from 'node:assert/strict'; import { createVerify, generateKeyPairSync } from 'node:crypto'; -import { readdirSync, readFileSync } from 'node:fs'; -import { join } from 'node:path'; +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { dirname, join } from 'node:path'; import { test } from 'node:test'; import { runJob } from '../testing/job.ts'; @@ -104,8 +104,17 @@ test('a repo job is logged in to the forge’s image registry with its own token 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, 'npmrc')); - assert.equal(readFileSync(join(job.temp, 'npmrc'), 'utf8'), '//npm.pkg.github.com/:_authToken=ghs_job\n'); + 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', () => { @@ -160,6 +169,27 @@ test('a key pasted into a one-line field gets its lines back before the agent re 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], @@ -198,6 +228,43 @@ test('a deploy job is handed a token of the tenant’s App that may read the ope } }); +/** 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); @@ -237,7 +304,7 @@ test('on a forge runner, a repo job of a repo with a cache host on netbird joins 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'], SETUP_KEY]); + 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', @@ -306,3 +373,18 @@ test('a deploy job whose join fails fails', () => { 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/testing/job.ts b/packages/cli-ci/src/testing/job.ts index 4952be65..84887037 100644 --- a/packages/cli-ci/src/testing/job.ts +++ b/packages/cli-ci/src/testing/job.ts @@ -7,8 +7,9 @@ // tsconfig). // // op `op read ` answers from `vault`, else fails as op does -// curl the forge's API: a repository's installation, and a token for it; -// any other download, a key +// 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 @@ -55,10 +56,21 @@ switch (tool) { break; } const url = /^url = "(.*)"$/m.exec(input)[1]; - if (url.endsWith('/installation')) process.stdout.write(JSON.stringify({ id: 42 })); - else if (url.endsWith('/app/installations/42/access_tokens')) - process.stdout.write(JSON.stringify({ token: 'ghs_operations', expires_at: '2026-12-02T05:00:00Z' })); - else fail('curl: (22) The requested URL returned error: 404'); + 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': { @@ -116,7 +128,12 @@ function handed(path: string): Record { */ export function runJob( args: string[], - options: { env?: Record; vault?: Record; netbirdFails?: boolean } = {}, + options: { + env?: Record; + vault?: Record; + netbirdFails?: boolean; + apiStatus?: number; + } = {}, ): Job { const dir = mkdtempSync(join(tmpdir(), 'plx-ci-setup-')); const bin = join(dir, 'bin'); @@ -149,6 +166,7 @@ export function runJob( FAKE_LOG: join(dir, 'calls'), FAKE_VAULT: vault, ...(options.netbirdFails ? { FAKE_NETBIRD_FAILS: '1' } : {}), + ...(options.apiStatus ? { FAKE_API_STATUS: String(options.apiStatus) } : {}), ...options.env, }, }); From e8113e3c517c8392e93454d27ad31e4edfe0ebee Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:44:58 +0100 Subject: [PATCH 15/15] Setup: the cache host for the repo job alone, keys masked as restored, the App's errors named (PLX-227) - A deploy job waits for the network map, never for the cache host: its key reaches the app hosts alone. - keyLines masks every line it returns, so a key pasted into a one-line field is masked line by line however it is printed later, -v included. - The App's calls read the HTTP status with write-out instead of fail-with-body: a 401 and a 404 each end in one line naming the App's client ID and the operations repo; the unreachable line for a missing installation is gone. - Under --dry-run a deploy job calls no API. - The Docker config and the npmrc are written 0600 in directories 0700; the npmrc in a directory of its own. - A job joins the overlay as ci--, so the two joins of a run never meet each other's peer. Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.ts | 21 ++++--- packages/cli-ci/src/core/setup.ts | 80 +++++++++++++++++++-------- 2 files changed, 70 insertions(+), 31 deletions(-) diff --git a/packages/cli-ci/src/commands/setup.ts b/packages/cli-ci/src/commands/setup.ts index aedd73d2..bd283ba9 100644 --- a/packages/cli-ci/src/commands/setup.ts +++ b/packages/cli-ci/src/commands/setup.ts @@ -20,23 +20,28 @@ // 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. +// 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, its lines restored where it was pasted into a one-line -// field. +// deploy key. // 5. On a forge runner, where step 1 read a setup key: join the overlay as -// an ephemeral peer, and wait until the cache host resolves (repo) or -// the network map names a peer (deploy). A repo job that cannot join -// goes on without the remote cache and warns on the run; a deploy job -// fails. +// 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 @@ -46,7 +51,7 @@ // 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, mints no token, and writes and starts +// 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 diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts index 20838276..28d403aa 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -1,7 +1,7 @@ // 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 { join } from 'node:path'; +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'; @@ -63,25 +63,23 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro // 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( - run('mkdir', ['-p', docker]), - write(join(docker, 'config.json'), `${JSON.stringify({ auths: { [IMAGE_REGISTRY]: { auth } } })}\n`), - ); + 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, 'npmrc'); - plan.push(write(npmrc, `//${PACKAGE_REGISTRY}/:_authToken=${token}\n`)); + const npmrc = join(temp, 'npm', 'npmrc'); + plan.push(...login(npmrc, `//${PACKAGE_REGISTRY}/:_authToken=${token}\n`)); variables.NPM_CONFIG_USERCONFIG = npmrc; } } else { - const sshKey = keyLines(await vault.read(`op://${vaultName}/deploy-ssh/private key?ssh-format=openssh`)); + 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(await vault.read(`op://${vaultName}/github-app/private-key`)); + 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; @@ -102,7 +100,12 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro await ctx.apply(plan); if (setupKey) { try { - await joinOverlay(ctx, { setupKey, hostname: `ci-${need('GITHUB_RUN_ID', env)}`, waitFor: cacheHost }); + // 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. @@ -177,17 +180,25 @@ function hand(ctx: Context, what: string, file: () => string, values: Record { + 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) }); - return JSON.parse(out) as { id?: number; token?: string }; + 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`); - if (!id) throw new Error(`the tenant’s App is not installed on ${owner}/${repo}`); - if (ctx.dryRun) return undefined; const { token } = await call('POST', `/app/installations/${id}/access_tokens`, { repositories: [repo], permissions: { contents: 'read' }, @@ -230,17 +251,30 @@ async function operationsToken( return token; } -/** A request for `curl -K -`: the credential on stdin, never on argv, where a process listing would show it. */ +/** 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}"`, - 'fail-with-body', '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`;