Authenticate WebSocket connections and bind command results to their worker
Security / JS Security (npm audit) (push) Failing after 16s
Lint / JS (eslint) (push) Successful in 18s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Test / JS Tests (jest) (push) Successful in 15s
Lint / JS (eslint) (pull_request) Successful in 13s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / JS Security (npm audit) (pull_request) Failing after 17s
Test / JS Tests (jest) (pull_request) Successful in 15s
Security / JS Security (npm audit) (push) Failing after 16s
Lint / JS (eslint) (push) Successful in 18s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Test / JS Tests (jest) (push) Successful in 15s
Lint / JS (eslint) (pull_request) Successful in 13s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / JS Security (npm audit) (pull_request) Failing after 17s
Test / JS Tests (jest) (pull_request) Successful in 15s
Any client that could reach :8080 got a WebSocket connection. Every connection started as a browser client and received every broadcast. worker_connect accepted a missing api_key, so anyone could register under an existing worker's name and receive its commands. command_result was accepted from any connection, so execution logs could be forged. - Classify each upgrade in verifyClient (lib/wsauth.js). A request is: - browser: a trusted-proxy Authelia identity in an allowed group; - worker: Authorization: Bearer <WORKER_API_KEY>; - pending: neither, allowed only while WORKER_AUTH_ENFORCE is off; - rejected (401): everything else, and always for a wrong key. - Only browser connections receive broadcasts. A pending connection may send only worker_connect and is closed after 30 s if it doesn't identify. - worker_connect requires the key. A keyless worker is allowed with a warning until WORKER_AUTH_ENFORCE=1, so existing workers keep working until they are updated. - Record which worker each command was sent to. command_result is accepted only from that worker (matched by DB id, so a reconnect mid-command still works) and only once. pong no longer trusts a client-supplied id. - Worker, heartbeat and Gandalf keys use a constant-time compare. Log an error at startup if WORKER_API_KEY is unset. - The worker sends its key at the handshake and in worker_connect. Closes #38 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b8a7b2c3b9
commit
ac6c6c72c5
5 files changed
+283
-22
No files matched your search
@@ -14,10 +14,24 @@ const { validateWebhookUrl, applyParams, evalCondition, calculateNextRun } = req
|
||||
const { PAGES } = require('./lib/nav');
|
||||
const { renderPage, renderError } = require('./lib/render');
|
||||
const { upsertUser, makeAuthenticatePage, ssoIdentity, trustedProxies } = require('./lib/pageauth');
|
||||
const { safeEqual, checkWorkerKey, workerAuthEnforced, classifyUpgrade, allowWorkerConnect } = require('./lib/wsauth');
|
||||
|
||||
const app = express();
|
||||
const server = http.createServer(app);
|
||||
const wss = new WebSocket.Server({ server });
|
||||
// Authenticate every WebSocket upgrade (see lib/wsauth.js). Rejected handshakes get a 401
|
||||
// before the upgrade completes; the classification is kept on the request for 'connection'.
|
||||
const wss = new WebSocket.Server({
|
||||
server,
|
||||
verifyClient: ({ req }) => {
|
||||
const kind = classifyUpgrade(req);
|
||||
req.pulseKind = kind;
|
||||
if (kind === 'reject') {
|
||||
const addr = (req.socket && req.socket.remoteAddress) || '';
|
||||
console.warn(`[Security] WebSocket upgrade rejected from ${JSON.stringify(addr)}`);
|
||||
}
|
||||
return kind !== 'reject';
|
||||
}
|
||||
});
|
||||
|
||||
// Dev/read-only guard: skip every background job that writes to the database.
|
||||
const DEV_READONLY = process.env.PULSE_DEV_READONLY === '1' || process.env.DISABLE_BACKGROUND_JOBS === '1';
|
||||
@@ -343,13 +357,13 @@ async function processScheduledCommands() {
|
||||
);
|
||||
|
||||
// Send command to worker
|
||||
workerWs.send(JSON.stringify({
|
||||
sendCommandToWorker(workerWs, {
|
||||
type: 'execute_command',
|
||||
execution_id: executionId,
|
||||
command: schedule.command,
|
||||
worker_id: workerId,
|
||||
timeout: 5 * 60_000 // SCHEDULED_CMD_TIMEOUT
|
||||
}));
|
||||
});
|
||||
|
||||
broadcast({ type: 'execution_started', execution_id: executionId, workflow_id: null });
|
||||
}
|
||||
@@ -400,19 +414,62 @@ const browserClients = new Set(); // Browser UI connections
|
||||
const workerClients = new Set(); // Worker agent connections
|
||||
const workers = new Map(); // Map worker_id -> WebSocket connection
|
||||
|
||||
wss.on('connection', (ws) => {
|
||||
// Default to browser client until worker_connect identifies it as a worker
|
||||
browserClients.add(ws);
|
||||
// Which worker each in-flight command was sent to, keyed by command_id (workflow steps)
|
||||
// or execution_id (quick/scheduled/internal commands). Results from any other
|
||||
// connection are dropped, so a connection cannot forge another worker's output.
|
||||
// The DB worker id is used rather than the socket so a worker that reconnects
|
||||
// mid-command can still deliver its result.
|
||||
const _commandTargets = new Map(); // key → { dbWorkerId, sentAt }
|
||||
const COMMAND_TARGET_TTL_MS = 25 * 60 * 60_000; // longer than any command or wait step
|
||||
|
||||
function sendCommandToWorker(workerWs, message) {
|
||||
const key = message.command_id || message.execution_id;
|
||||
_commandTargets.set(key, { dbWorkerId: workerWs.dbWorkerId, sentAt: Date.now() });
|
||||
workerWs.send(JSON.stringify(message));
|
||||
}
|
||||
|
||||
// Entries for commands whose result never arrives would otherwise accumulate.
|
||||
setInterval(() => {
|
||||
const cutoff = Date.now() - COMMAND_TARGET_TTL_MS;
|
||||
for (const [key, t] of _commandTargets) {
|
||||
if (t.sentAt < cutoff) _commandTargets.delete(key);
|
||||
}
|
||||
}, 60 * 60_000).unref();
|
||||
|
||||
const PENDING_IDENTIFY_MS = 30_000; // unauthenticated connections must identify as a worker within this
|
||||
|
||||
wss.on('connection', (ws, req) => {
|
||||
ws.kind = req.pulseKind || 'pending';
|
||||
ws.isWorker = false;
|
||||
// Only authenticated browser sessions receive the live event feed.
|
||||
if (ws.kind === 'browser') browserClients.add(ws);
|
||||
if (ws.kind === 'pending') {
|
||||
ws.identifyTimer = setTimeout(() => {
|
||||
if (!ws.isWorker) ws.close(4001, 'Unauthorized');
|
||||
}, PENDING_IDENTIFY_MS);
|
||||
}
|
||||
|
||||
// Handle incoming messages from workers
|
||||
ws.on('message', async (data) => {
|
||||
try {
|
||||
const message = JSON.parse(data.toString());
|
||||
|
||||
// Before identifying, a connection may only send worker_connect.
|
||||
if (!ws.isWorker && message.type !== 'worker_connect') return;
|
||||
|
||||
if (message.type === 'command_result') {
|
||||
// Handle command result from worker
|
||||
const { execution_id, command_id, worker_id, success, stdout, stderr, duration, timestamp } = message;
|
||||
|
||||
const targetKey = command_id || execution_id;
|
||||
const target = _commandTargets.get(targetKey);
|
||||
if (!target || target.dbWorkerId !== ws.dbWorkerId) {
|
||||
console.warn(`[Security] Dropped command_result for ${JSON.stringify(targetKey)} from worker ` +
|
||||
`${JSON.stringify(ws.dbWorkerId)}: ${target ? 'sent to a different worker' : 'no such command in flight'}`);
|
||||
return;
|
||||
}
|
||||
_commandTargets.delete(targetKey);
|
||||
|
||||
// Add result to execution logs
|
||||
await addExecutionLog(execution_id, {
|
||||
step: 'command_execution',
|
||||
@@ -496,13 +553,20 @@ wss.on('connection', (ws) => {
|
||||
}
|
||||
|
||||
if (message.type === 'worker_connect') {
|
||||
// Authenticate worker — reject if api_key is provided but wrong
|
||||
const { worker_id, worker_name, api_key } = message;
|
||||
if (api_key && api_key !== process.env.WORKER_API_KEY) {
|
||||
console.warn(`[Security] Worker connection rejected: invalid API key from "${worker_name}"`);
|
||||
if (ws.isWorker) return; // already identified; ignore repeats
|
||||
const auth = allowWorkerConnect(ws.kind, api_key);
|
||||
if (!auth.ok) {
|
||||
console.warn(`[Security] Worker connection rejected: missing or invalid API key from ${JSON.stringify(worker_name)}`);
|
||||
ws.close(4001, 'Unauthorized');
|
||||
return;
|
||||
}
|
||||
if (auth.legacy) {
|
||||
console.warn(`[Security] Worker ${JSON.stringify(worker_name)} connected without an API key. ` +
|
||||
'Update the worker; keyless workers are refused once WORKER_AUTH_ENFORCE=1.');
|
||||
}
|
||||
clearTimeout(ws.identifyTimer);
|
||||
ws.isWorker = true;
|
||||
// Move from browser set to worker set
|
||||
browserClients.delete(ws);
|
||||
workerClients.add(ws);
|
||||
@@ -551,8 +615,8 @@ wss.on('connection', (ws) => {
|
||||
}
|
||||
|
||||
if (message.type === 'pong') {
|
||||
// Use the DB worker ID stored on connect; fall back to message payload
|
||||
const dbId = ws.dbWorkerId || message.worker_id;
|
||||
// Only the DB worker ID bound at worker_connect; never a client-supplied id.
|
||||
const dbId = ws.dbWorkerId;
|
||||
if (dbId) {
|
||||
await pool.query(
|
||||
`UPDATE workers SET last_heartbeat=NOW() WHERE id=?`,
|
||||
@@ -567,6 +631,7 @@ wss.on('connection', (ws) => {
|
||||
});
|
||||
|
||||
ws.on('close', () => {
|
||||
clearTimeout(ws.identifyTimer);
|
||||
browserClients.delete(ws);
|
||||
workerClients.delete(ws);
|
||||
if (ws.workerId) {
|
||||
@@ -721,7 +786,7 @@ async function authenticateSSO(req, res, next) {
|
||||
// Gandalf machine-to-machine API key auth
|
||||
function authenticateGandalf(req, res, next) {
|
||||
const apiKey = req.headers['x-gandalf-api-key'];
|
||||
if (!apiKey || apiKey !== process.env.GANDALF_API_KEY) {
|
||||
if (!safeEqual(apiKey, process.env.GANDALF_API_KEY)) {
|
||||
return res.status(401).json({ error: 'Unauthorized' });
|
||||
}
|
||||
req.user = { username: 'gandalf:link_stats', isAdmin: false };
|
||||
@@ -1057,14 +1122,14 @@ async function executeCommandStep(executionId, step, stepNumber, params = {}) {
|
||||
? Math.min(Math.max(parseInt(step.timeout, 10) * 1000, 5000), 600000)
|
||||
: COMMAND_TIMEOUT_MS;
|
||||
|
||||
workerWs.send(JSON.stringify({
|
||||
sendCommandToWorker(workerWs, {
|
||||
type: 'execute_command',
|
||||
execution_id: executionId,
|
||||
command_id: commandId,
|
||||
command: command,
|
||||
worker_id: workerId,
|
||||
timeout: stepTimeoutMs
|
||||
}));
|
||||
});
|
||||
|
||||
// Per-step retry: step.retries (default 0) with step.retryDelayMs (default 2000)
|
||||
const maxRetries = Math.min(parseInt(step.retries || 0, 10), 5);
|
||||
@@ -1092,10 +1157,10 @@ async function executeCommandStep(executionId, step, stepNumber, params = {}) {
|
||||
step: stepNumber, action: 'command_sent', worker_id: workerId,
|
||||
command: command, command_id: retryCommandId, timestamp: new Date().toISOString()
|
||||
});
|
||||
workerWs.send(JSON.stringify({
|
||||
sendCommandToWorker(workerWs, {
|
||||
type: 'execute_command', execution_id: executionId, command_id: retryCommandId,
|
||||
command: command, worker_id: workerId, timeout: stepTimeoutMs
|
||||
}));
|
||||
});
|
||||
commandId = retryCommandId; // update for next waitForCommandResult call
|
||||
}
|
||||
results.push(result);
|
||||
@@ -1258,7 +1323,7 @@ app.post('/api/workers/heartbeat', async (req, res) => {
|
||||
const apiKey = req.headers['x-api-key'];
|
||||
|
||||
// Verify API key — reject missing or wrong keys
|
||||
if (!apiKey || apiKey !== process.env.WORKER_API_KEY) {
|
||||
if (!checkWorkerKey(apiKey)) {
|
||||
return res.status(401).json({ error: 'Invalid API key' });
|
||||
}
|
||||
|
||||
@@ -1639,13 +1704,13 @@ app.post('/api/internal/command', authenticateGandalf, async (req, res) => {
|
||||
}])]
|
||||
);
|
||||
|
||||
workerWs.send(JSON.stringify({
|
||||
sendCommandToWorker(workerWs, {
|
||||
type: 'execute_command',
|
||||
execution_id: executionId,
|
||||
command: command,
|
||||
worker_id: worker_id,
|
||||
timeout: QUICK_CMD_TIMEOUT_MS
|
||||
}));
|
||||
});
|
||||
|
||||
res.json({ execution_id: executionId });
|
||||
} catch (error) {
|
||||
@@ -1804,7 +1869,7 @@ app.post('/api/workers/:id/command', authenticateSSO, requireJSON, async (req, r
|
||||
return res.status(400).json({ error: 'Worker not connected' });
|
||||
}
|
||||
|
||||
workerWs.send(JSON.stringify(commandMessage));
|
||||
sendCommandToWorker(workerWs, commandMessage);
|
||||
console.log(`Command sent to worker ${workerId}: ${command}`);
|
||||
|
||||
broadcast({ type: 'execution_started', execution_id: executionId, workflow_id: null });
|
||||
@@ -1849,6 +1914,10 @@ initDatabase().then(() => {
|
||||
'Set it to the reverse proxy address(es) that run Authelia forward auth.');
|
||||
}
|
||||
console.log(`Worker API Key configured: ${process.env.WORKER_API_KEY ? 'Yes' : 'No'}`);
|
||||
if (!process.env.WORKER_API_KEY) {
|
||||
console.error('ERROR: WORKER_API_KEY is not set, so no worker can authenticate.');
|
||||
}
|
||||
console.log(`Worker auth enforcement: ${workerAuthEnforced() ? 'ON (keyless workers refused)' : 'OFF (keyless workers allowed with a warning; set WORKER_AUTH_ENFORCE=1 once all workers send their key)'}`);
|
||||
if (DEV_READONLY) {
|
||||
console.warn('************************************************************');
|
||||
console.warn('* PULSE_DEV_READONLY IS ON — background jobs are disabled *');
|
||||
|
||||
Reference in new issue
Block a user