Integration tests for the Gandalf contract, auth and reliability; fix worker offline status
CI / Lint (eslint) (push) Successful in 46s
CI / Security (npm audit) (push) Successful in 26s
CI / Integration (api) (push) Successful in 1m31s
CI / Test (jest) (pull_request) Successful in 50s
CI / UI (playwright) (push) Successful in 2m31s
CI / Integration (api) (pull_request) Successful in 1m58s
CI / Test (jest) (push) Successful in 13s
CI / Deploy (push) Skipped
CI / Notify (push) Skipped
CI / UI (playwright) (pull_request) Successful in 2m16s
CI / Lint (eslint) (pull_request) Successful in 15s
CI / Security (npm audit) (pull_request) Successful in 15s
CI / Deploy (pull_request) Skipped
CI / Notify (pull_request) Skipped

New CI job `Integration (api)` (#45 phase 3) runs the real server and three
workers on Node 20 against MariaDB and tests them as a black box over HTTP
and WebSocket (20 tests, about 12 s):

- Gandalf contract: submit and poll, stdout from command_result, failures
  with exit code and stderr, 401 for wrong or missing key, 400 for missing
  fields or an unknown worker, 404 for an unknown execution
- Auth: SSO identity, 401/403, heartbeat key, /healthz exposes only status;
  WebSocket upgrade refused without credentials, with a wrong key or a wrong
  group; live events reach a signed-in browser; a browser socket cannot
  forge a command result
- Reliability: a worker killed mid-command fails the execution at once; a
  worker at capacity answers with a failure; an aborted execution stays
  failed when the late result arrives; a disconnected worker shows offline

The last test found a bug from #42: the close handler deleted the worker's
runtime-id entry before checking whether the socket was still live under its
database id, and the two ids are normally the same key. So a disconnected
worker was never marked offline and showed 'online' until the stale
heartbeat sweep. Gandalf was unaffected (it checks live sockets).

MariaDB setup for CI moves to scripts/ci/mariadb.sh, shared by both jobs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-22 14:14:28 -05:00
1 parent 1d5b8cdd53
commit def926d41e
11 files changed
+391 -21

No files matched your search

+77
View File
@@ -0,0 +1,77 @@
'use strict';
// HTTP and WebSocket authentication (#37, #38).
const { api, sso, SSO, WORKER_KEY, openWs, workerByName, waitFor, gandalf, waitForExecution, commandResult } = require('./helpers');
describe('HTTP', () => {
test('a trusted SSO identity in an allowed group is signed in', async () => {
const r = await sso('GET', '/api/user');
expect(r.status).toBe(200);
expect(r.json.username).toBe('int.tester');
});
test('no identity is 401, and a group outside the allowed list is 403', async () => {
expect((await api('GET', '/api/user')).status).toBe(401);
expect((await api('GET', '/api/user', { headers: { ...SSO, 'Remote-Groups': 'guests' } })).status).toBe(403);
});
test('worker heartbeats need the worker key', async () => {
const r = await api('POST', '/api/workers/heartbeat', {
headers: { 'X-API-Key': 'wrong' }, body: { worker_id: 'x', name: 'x' },
});
expect(r.status).toBe(401);
});
test('the public health check reveals no detail beyond status', async () => {
const r = await api('GET', '/healthz');
expect(r.status).toBe(200);
expect(Object.keys(r.json).sort()).toEqual(['db', 'sha', 'status', 'uptime_s', 'version', 'workers']);
});
});
describe('WebSocket upgrade', () => {
test('is refused with no credentials (worker auth is enforced)', async () => {
await expect(openWs()).rejects.toMatchObject({ status: 401 });
});
test('is refused with a wrong worker key', async () => {
await expect(openWs({ Authorization: 'Bearer wrong-key' })).rejects.toMatchObject({ status: 401 });
});
test('is refused for an SSO identity outside the allowed groups', async () => {
await expect(openWs({ ...SSO, 'Remote-Groups': 'guests' })).rejects.toBeDefined();
});
test('accepts the worker key', async () => {
const ws = await openWs({ Authorization: `Bearer ${WORKER_KEY}` });
ws.close();
});
test('a signed-in browser receives live execution events', async () => {
const ws = await openWs(SSO);
try {
const workerId = (await workerByName('node-02')).id;
const submit = await gandalf('POST', '/api/internal/command', { worker_id: workerId, command: 'echo live' });
const id = submit.json.execution_id;
await waitFor(() => ws.messages.some(m => m.type === 'command_result' && m.execution_id === id),
{ what: 'a command_result broadcast' });
} finally { ws.close(); }
});
test('a browser connection cannot forge a command result', async () => {
const ws = await openWs(SSO);
try {
const workerId = (await workerByName('node-03')).id;
const submit = await gandalf('POST', '/api/internal/command', { worker_id: workerId, command: 'sleep 1; echo genuine' });
const id = submit.json.execution_id;
ws.send(JSON.stringify({
type: 'command_result', execution_id: id, worker_id: workerId, command_id: id,
success: true, stdout: 'forged', stderr: '',
}));
const ex = await waitForExecution(id);
expect(ex.status).toBe('completed');
expect(commandResult(ex).stdout.trim()).toBe('genuine');
expect((ex.logs || []).filter(l => l.action === 'command_result')).toHaveLength(1);
} finally { ws.close(); }
});
});
+55
View File
@@ -0,0 +1,55 @@
'use strict';
// The contract Gandalf depends on (gandalf/monitor.py PulseClient.run_command):
// POST /api/internal/command -> {execution_id}; poll GET /api/internal/executions/:id
// until status is 'completed' (stdout read from the command_result log) or 'failed'.
const { gandalf, workerByName, waitForExecution, commandResult } = require('./helpers');
let workerId;
beforeAll(async () => {
workerId = (await workerByName('node-01')).id;
});
test('a command runs and its stdout comes back the way Gandalf reads it', async () => {
const submit = await gandalf('POST', '/api/internal/command', { worker_id: workerId, command: 'echo REACHABLE' });
expect(submit.status).toBe(200);
expect(submit.json.execution_id).toMatch(/^[0-9a-f-]{36}$/);
const ex = await waitForExecution(submit.json.execution_id);
expect(ex.status).toBe('completed');
expect(ex.started_by).toBe('gandalf:link_stats');
expect(commandResult(ex).stdout.trim()).toBe('REACHABLE');
});
test('a failing command ends as failed, with the exit code and stderr kept', async () => {
const submit = await gandalf('POST', '/api/internal/command', { worker_id: workerId, command: 'echo oops >&2; exit 4' });
const ex = await waitForExecution(submit.json.execution_id);
expect(ex.status).toBe('failed');
const r = commandResult(ex);
expect(r.success).toBe(false);
expect(r.exit_code).toBe(4);
expect(r.stderr).toContain('oops');
});
test.each([
['a wrong key', 'not-the-key'],
['no key', null],
])('%s is refused on both endpoints', async (_label, key) => {
const submit = await gandalf('POST', '/api/internal/command', { worker_id: workerId, command: 'true' }, key);
expect(submit.status).toBe(401);
const poll = await gandalf('GET', '/api/internal/executions/00000000-0000-0000-0000-000000000000', undefined, key);
expect(poll.status).toBe(401);
});
test('missing fields and unknown workers are rejected without creating an execution', async () => {
expect((await gandalf('POST', '/api/internal/command', { worker_id: workerId })).status).toBe(400);
expect((await gandalf('POST', '/api/internal/command', { command: 'true' })).status).toBe(400);
const unknown = await gandalf('POST', '/api/internal/command', { worker_id: 'no-such-worker', command: 'true' });
expect(unknown.status).toBe(400);
expect(unknown.json.error).toBe('Worker not connected');
});
test('an unknown execution id is a 404', async () => {
const r = await gandalf('GET', '/api/internal/executions/00000000-0000-0000-0000-000000000000');
expect(r.status).toBe(404);
});
+112
View File
@@ -0,0 +1,112 @@
'use strict';
const { spawn } = require('child_process');
const path = require('path');
const WebSocket = require('ws');
// Matches scripts/ci/ui-stack.sh.
const BASE = process.env.PULSE_URL || 'http://127.0.0.1:8400';
const WS_BASE = BASE.replace(/^http/, 'ws');
const WORKER_KEY = process.env.PULSE_TEST_WORKER_KEY || 'ui-test-worker-key';
const GANDALF_KEY = process.env.PULSE_TEST_GANDALF_KEY || 'ui-test-gandalf-key';
const SSO = {
'Remote-User': 'int.tester',
'Remote-Name': 'Integration Tester',
'Remote-Email': 'int@example.invalid',
'Remote-Groups': 'admin',
};
async function api(method, url, { headers = {}, body } = {}) {
const res = await fetch(BASE + url, {
method,
headers: { ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...headers },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json = null;
try { json = JSON.parse(text); } catch { /* not JSON */ }
return { status: res.status, json, text };
}
const sso = (method, url, body) => api(method, url, { headers: SSO, body });
const gandalf = (method, url, body, key = GANDALF_KEY) =>
api(method, url, { headers: key === null ? {} : { 'X-Gandalf-API-Key': key }, body });
async function waitFor(fn, { timeout = 20_000, interval = 250, what = 'condition' } = {}) {
const end = Date.now() + timeout;
let last;
while (Date.now() < end) {
last = await fn();
if (last) return last;
await new Promise(r => setTimeout(r, interval));
}
throw new Error(`timed out waiting for ${what} (last value: ${JSON.stringify(last)})`);
}
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function workerByName(name) {
const { json } = await sso('GET', '/api/workers');
return (json || []).find(w => w.name === name);
}
// Polls the Gandalf endpoint the way Gandalf does, until the execution leaves 'running'.
async function waitForExecution(id, opts = {}) {
return waitFor(async () => {
const r = await gandalf('GET', `/api/internal/executions/${id}`);
return r.json && r.json.status !== 'running' ? r.json : null;
}, { what: `execution ${id} to finish`, ...opts });
}
const commandResult = ex => (ex.logs || []).find(l => l.action === 'command_result');
// An extra worker process owned by one test, so it can be killed or limited.
async function startWorker(name, env = {}) {
const child = spawn(process.execPath, [path.join(__dirname, '..', '..', 'worker', 'worker.js')], {
cwd: __dirname, // no .env here
env: {
...process.env,
WORKER_NAME: name, PULSE_SERVER: BASE, PULSE_WS: WS_BASE,
WORKER_API_KEY: WORKER_KEY, HEARTBEAT_INTERVAL: '5', ...env,
},
stdio: ['ignore', 'pipe', 'pipe'],
});
let log = '';
child.stdout.on('data', d => { log += d; });
child.stderr.on('data', d => { log += d; });
const worker = await waitFor(async () => {
const w = await workerByName(name);
return w && w.status === 'online' ? w : null;
}, { what: `worker ${name} to come online` }).catch(e => { child.kill('SIGKILL'); throw new Error(`${e.message}\n${log}`); });
return {
id: worker.id,
child,
log: () => log,
async stop() {
if (child.exitCode === null && child.signalCode === null) {
child.kill('SIGKILL');
await new Promise(r => child.once('exit', r));
}
// Remove it so other suites (and the UI tests' worker counts) don't see it.
await waitFor(async () => (await workerByName(name))?.status === 'offline', { timeout: 5_000, what: `${name} to show offline` });
await sso('DELETE', `/api/workers/${worker.id}`);
},
};
}
// Opens a WebSocket and resolves once open, or rejects with the HTTP status if refused.
function openWs(headers = {}) {
return new Promise((resolve, reject) => {
const ws = new WebSocket(WS_BASE, { headers });
const messages = [];
ws.on('message', d => { try { messages.push(JSON.parse(d)); } catch { /* ignore */ } });
ws.once('open', () => resolve(Object.assign(ws, { messages })));
ws.once('unexpected-response', (req, res) => reject(Object.assign(new Error(`HTTP ${res.statusCode}`), { status: res.statusCode })));
ws.once('error', reject);
});
}
module.exports = {
BASE, SSO, GANDALF_KEY, WORKER_KEY, api, sso, gandalf, waitFor, sleep,
workerByName, waitForExecution, commandResult, startWorker, openWs,
};
+11
View File
@@ -0,0 +1,11 @@
'use strict';
// Integration tests: black-box tests against a running Pulse stack (real server,
// MariaDB and workers), started by scripts/ci/ui-stack.sh. See README "Integration tests".
module.exports = {
rootDir: __dirname,
testMatch: ['**/*.int.js'],
testEnvironment: 'node',
testTimeout: 60_000,
maxWorkers: 1, // one shared stack: suites must not race each other
};
+62
View File
@@ -0,0 +1,62 @@
'use strict';
// Executions always reach a final state (#7), and a final state is final.
const { sso, gandalf, startWorker, waitForExecution, commandResult, sleep, waitFor, workerByName } = require('./helpers');
const unique = () => `int-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
test('a worker that dies mid-command fails the execution at once, not hours later', async () => {
const w = await startWorker(unique());
try {
const submit = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: 'sleep 30' });
expect(submit.status).toBe(200);
await sleep(500);
w.child.kill('SIGKILL');
const ex = await waitForExecution(submit.json.execution_id, { timeout: 15_000 });
expect(ex.status).toBe('failed');
expect(commandResult(ex).error).toMatch(/disconnected/i);
} finally { await w.stop(); }
});
test('a worker that disconnects shows offline at once', async () => {
const name = unique();
const w = await startWorker(name);
try {
w.child.kill('SIGKILL');
// Not after the stale-heartbeat sweep: the socket close marks it offline.
await waitFor(async () => (await workerByName(name))?.status === 'offline', { timeout: 3_000, what: 'offline status' });
} finally { await w.stop(); }
});
test('a worker at capacity answers with a failure instead of staying silent', async () => {
const w = await startWorker(unique(), { MAX_CONCURRENT_TASKS: '1' });
try {
const first = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: 'sleep 3; echo first' });
await sleep(300);
const second = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: 'echo second' });
const ex2 = await waitForExecution(second.json.execution_id, { timeout: 10_000 });
expect(ex2.status).toBe('failed');
expect(commandResult(ex2).error).toMatch(/capacity/i);
const ex1 = await waitForExecution(first.json.execution_id);
expect(ex1.status).toBe('completed');
} finally { await w.stop(); }
});
test('an aborted execution stays failed when the worker reports back later', async () => {
const w = await startWorker(unique());
try {
const submit = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: 'sleep 2; echo late' });
const id = submit.json.execution_id;
await sleep(300);
expect((await sso('POST', `/api/executions/${id}/abort`)).status).toBe(200);
await sleep(3500); // the command finishes and the worker sends its result
const ex = await waitForExecution(id);
expect(ex.status).toBe('failed');
expect((ex.logs || []).some(l => l.action === 'execution_aborted')).toBe(true);
expect((ex.logs || []).some(l => l.action === 'command_result' && l.success)).toBe(false);
} finally { await w.stop(); }
});