Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Coach: der Test-Lauf laeuft, und CI kann die Jobs ueberhaupt erreichen

Duarte Santosde7f25cbe77c
diff --git a/api/coach/adapters/spawn.js b/api/coach/adapters/spawn.js
index 3f487ebe2..1284ae92a 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 f870c9c42..9d095db2c 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 ffd51215b..f7de36c21 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 2f5fc6b4d..b0cbccb3d 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 207162029..64c9466a6 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' });
+ }
});