From de7f25cbe77c4e1b4030d50adcfcf85626e3bfdf Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 4 Aug 2026 16:11:43 +0200 Subject: [PATCH] Coach: der Test-Lauf laeuft, und CI kann die Jobs ueberhaupt erreichen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drei Sachen, die nie gelaufen sind, weil die CI fuer die api noch nicht existierte. canDropPrivileges faellt unter Linux zu, solange der Prozess nicht root ist und kein `coach`-User im Image steht. Ein CI-Runner ist Linux, laeuft als normaler User und hat keinen `coach` — also hat dort jedes enqueue() refused, und acht Tests waeren mit dem neuen api-Job rot geworden. Die Suite pinnt das Urteil jetzt selbst, statt es vom Host zu erben; der Test, dem die Verweigerung selbst gehoert, pinnt die Gegenrichtung und laeuft damit erstmals wirklich (vorher sprang er auf jedem Host raus, auf dem der Drop zufaellig klappte — und rief require() in einem ESM-Modul auf). testRun() griff auf ein `job`, das in seinem Scope nicht existiert: ReferenceError bei jedem Klick auf "Test the Coach", und weil der Wurf vor dem try lag, blieb jedes Mal ein Temp-Verzeichnis liegen. Ohne Nutzer gibt es kein Profil, das zahlt — im Instance-Modus ist das der gebundene Credential, im Profile-Modus niemand. Danach antwortete die Fixture auf den Test-Prompt mit einem ganzen Trainingsplan, weil ohne Payload-Fence auf 'create' geraten wird. Genau dieser fehlende Fence unterscheidet den Rundlauf von einem echten Job. Dazu zwei Kleinigkeiten: /api/coach/disclosure verriet den Provider an Nicht-Angemeldete, und der Poll, der ein Proposal verfallen laesst, lieferte als einziger kein cap-Feld zurueck. --- api/coach/adapters/spawn.js | 10 ++++++++++ api/coach/fixture-cli.mjs | 7 +++++++ api/coach/jobs.js | 10 ++++++++-- api/coach/routes.js | 5 ++++- api/test/jobs.test.js | 32 ++++++++++++++++++++++++++------ 5 files changed, 55 insertions(+), 9 deletions(-) diff --git a/api/coach/adapters/spawn.js b/api/coach/adapters/spawn.js index 3f487eb..1284ae9 100644 --- a/api/coach/adapters/spawn.js +++ b/api/coach/adapters/spawn.js @@ -42,8 +42,18 @@ export function unprivilegedIds() { * So on Linux it fails closed: no drop, no job. Elsewhere (a developer's macOS laptop, where * there is no `coach` user and no container boundary either) it stays permissive, because the * alternative is that the test suite and local development simply stop working. + * + * "Elsewhere" does not include CI, which is Linux, runs as an ordinary user and has no `coach` + * user — so the honest answer there is `false`, and every test that needs to reach the code + * behind the drop has to say so explicitly. That is what the seam below is for: the suite sets + * the verdict it wants to test against, including the refusal itself, instead of inheriting + * whatever the host it happens to run on would have said. */ +let forced = null; +/** Test-only. Pass a verdict to pin it, or null to go back to asking the host. */ +export function forcePrivilegeVerdict(v) { forced = v; } export function canDropPrivileges() { + if (forced) return forced; if (process.platform !== 'linux') return { ok: true, dropped: false, why: 'not linux — development host' }; if (unprivilegedIds()) return { ok: true, dropped: true, why: null }; if (process.getuid && process.getuid() !== 0) { diff --git a/api/coach/fixture-cli.mjs b/api/coach/fixture-cli.mjs index f870c9c..9d095db 100644 --- a/api/coach/fixture-cli.mjs +++ b/api/coach/fixture-cli.mjs @@ -32,6 +32,13 @@ if (MODE === 'invalid') { process.stdout.write('I am afraid I cannot do that.\n' const isRepair = /REPAIR REQUEST/i.test(prompt); if (MODE === 'invalid-then-valid' && !isRepair) { process.stdout.write('{"changes": "not an array"}\n'); process.exit(0); } +// The admin card's "Test the Coach": a prompt with no payload attached, asking for one small +// object back. A real provider answers that from the prompt alone, so the fixture does too — +// otherwise the single button that proves the runtime works is the one thing the shipped +// provider cannot do. Every genuine job embeds its payload in a fence (see buildPrompt), so +// the absence of one is what distinguishes the two. +if (!/```json/.test(prompt)) out({ coach_contract: 1, ok: true }); + // The payload the server built is embedded in the prompt between fences; pull it back out so // the answer references ids that actually exist. function payload() { diff --git a/api/coach/jobs.js b/api/coach/jobs.js index ffd5121..f7de36c 100644 --- a/api/coach/jobs.js +++ b/api/coach/jobs.js @@ -90,7 +90,9 @@ export function status(uid) { const rec = readUser(uid); if (rec.pending && rec.pending.expiresAt && rec.pending.expiresAt < Date.now()) { archive(uid, rec, 'expired'); - return { job: null, pending: null }; + // Same shape as every other answer: the poll that happens to be the one which expires a + // proposal must not be the one where the client's cap readout goes undefined. + return { job: null, pending: null, cap: capState(uid) }; } return { job: rec.current ? { id: rec.current.id, kind: rec.current.kind, state: rec.current.state, startedAt: rec.current.startedAt } : null, @@ -359,8 +361,12 @@ export async function testRun() { const adapter = adapterFor(cfg.provider); if (!adapter) return { ok: false, error: 'no provider configured' }; const jobDir = fs.mkdtempSync(path.join(os.tmpdir(), 'coach-test-')); - const env = cfgStore.jobEnv(jobDir, cfgStore.credentialFor(job.uid)); try { + // No user asked for this, so there is no profile whose account is being spent. In instance + // mode that is the bound profile's credential — the one the round-trip is meant to prove — + // and in per-profile mode it is nobody's, which is the honest answer: an admin cannot test + // a credential that belongs to a profile. + const env = cfgStore.jobEnv(jobDir, cfgStore.credentialFor(cfg.boundUid)); const ids = unprivilegedIds(); if (ids) fs.chownSync(jobDir, ids.uid, ids.gid); const check = await adapter.check(cfg, env); diff --git a/api/coach/routes.js b/api/coach/routes.js index 2f5fc6b..b0cbccb 100644 --- a/api/coach/routes.js +++ b/api/coach/routes.js @@ -41,8 +41,11 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) { /* ------------------------------ user ------------------------------ */ // What the consent screen has to disclose, straight from the module that builds payloads, - // so the screen cannot drift from what actually leaves (FR-09). + // so the screen cannot drift from what actually leaves (FR-09). Signed in only: the screen + // that reads it sits behind a session anyway, and on an invite-only instance which provider + // this box is wired to is nobody's business who has not been let in. 'GET /api/coach/disclosure': async (req, res) => { + if (!readSession(req)) return json(res, 401, { error: 'not signed in' }); const cfg = cfgStore.load(); json(res, 200, { provider: cfg.provider, diff --git a/api/test/jobs.test.js b/api/test/jobs.test.js index 2071620..64c9466 100644 --- a/api/test/jobs.test.js +++ b/api/test/jobs.test.js @@ -12,9 +12,17 @@ import { tempData, writeState, sampleState } from './helpers.mjs'; const DIR = tempData(); const cfg = await import('../coach/config.js'); const jobs = await import('../coach/jobs.js'); +const { forcePrivilegeVerdict } = await import('../coach/adapters/spawn.js'); cfg.save({ enabled: true, provider: 'fixture' }); +/* The privilege drop fails closed on Linux unless the server is root *and* the image has a + `coach` user — true in the container, false on a CI runner and false on most development + boxes. Left to the host, every test below that enqueues a job would pass or fail depending + on where it ran. So the verdict is pinned here, and the one test that cares about the + refusal pins the opposite verdict for its own duration. */ +forcePrivilegeVerdict({ ok: true, dropped: false, why: 'pinned by the test suite' }); + /** Jobs are async by design; the tests wait the way the client does — by polling status. */ async function settle(uid, ms = 15000) { const until = Date.now() + ms; @@ -140,13 +148,25 @@ test('the answer is carried no further than parsed — nothing here can apply it assert.equal(s.pending.proposal, undefined, 'no applyable proposal exists yet'); }); +test('the admin test-run completes a round trip without a user to spend', async () => { + // Every other path here starts from a profile; this one deliberately has none, which is + // exactly how it came to reference a job that does not exist in its scope. Nothing else in + // the suite touches the admin card's one button. + const r = await jobs.testRun(); + assert.equal(r.ok, true, r.error || 'the round trip failed'); + assert.equal(r.version, 'fixture'); +}); + test('a job is refused outright when the privilege drop cannot be performed', () => { - // Linux-only: on a developer's macOS box there is no container boundary to drop across, so - // canDropPrivileges stays permissive and there is nothing to assert. - if (process.platform !== 'linux') return; const uid = 'u-priv'; writeState(DIR, uid, sampleState()); - const { canDropPrivileges } = require('../coach/adapters/spawn.js'); - if (canDropPrivileges().ok) return; // running as root in CI with a coach user present - assert.throws(() => jobs.enqueue(uid, { kind: 'review' }), /switched off|disabled/i); + // The refusal is the assertion, so it is pinned rather than hoped for: this used to skip + // itself on any host where the drop happened to work, which is every host where the control + // matters least. + forcePrivilegeVerdict({ ok: false, dropped: false, why: 'no `coach` user exists in this image' }); + try { + assert.throws(() => jobs.enqueue(uid, { kind: 'review' }), e => e.code === 'unprivileged'); + } finally { + forcePrivilegeVerdict({ ok: true, dropped: false, why: 'pinned by the test suite' }); + } });