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

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:
jaredandClaude Opus 5.5 committed 2026-11-22 01:07:18 -05:00
1 parent b8a7b2c3b9
commit ac6c6c72c5
5 files changed
+283 -22

No files matched your search

+16
View File
@@ -424,6 +424,7 @@ DB_USER=pulse_user # Database user
DB_PASSWORD=<password> # Database password DB_PASSWORD=<password> # Database password
WORKER_API_KEY=<api-key> # Worker authentication key WORKER_API_KEY=<api-key> # Worker authentication key
TRUSTED_PROXIES=<ip>[,<ip/cidr>] # Proxies allowed to send Authelia identity headers (required, see below) TRUSTED_PROXIES=<ip>[,<ip/cidr>] # Proxies allowed to send Authelia identity headers (required, see below)
WORKER_AUTH_ENFORCE=1 # Refuse workers that don't send WORKER_API_KEY (see WebSocket authentication)
EXECUTION_RETENTION_DAYS=30 # Auto-cleanup retention (default: 30) EXECUTION_RETENTION_DAYS=30 # Auto-cleanup retention (default: 30)
# Web UI (all optional) # Web UI (all optional)
@@ -448,6 +449,21 @@ anywhere else are treated as not logged in, and are logged with their source add
closed: if `TRUSTED_PROXIES` is unset, no SSO login succeeds and a warning is printed at closed: if `TRUSTED_PROXIES` is unset, no SSO login succeeds and a warning is printed at
startup. Invalid entries are logged and skipped. Worker and Gandalf API-key routes don't use it. startup. Invalid entries are logged and skipped. Worker and Gandalf API-key routes don't use it.
### WebSocket authentication
Every WebSocket upgrade is authenticated. A browser connection must come through a trusted proxy
(see above) with an Authelia identity in the `admin` or `employee` group, and only those
connections receive the live event feed. A worker authenticates with
`Authorization: Bearer <WORKER_API_KEY>` at the handshake, and also sends the key in its
`worker_connect` message. A wrong key is always refused. Only a connection that identified as a
worker can deliver command results, and only for commands the server sent to that worker.
Workers older than this change don't send a key. Until every worker is updated, leave
`WORKER_AUTH_ENFORCE` unset: keyless workers are still accepted, with a `[Security]` warning
naming the worker, and an unauthenticated connection that doesn't identify as a worker within 30 s
is closed. Once the warnings stop, set `WORKER_AUTH_ENFORCE=1` and restart. From then on, upgrades
with no valid credentials get a 401.
### Local development against a real database ### Local development against a real database
Running a local instance against the production MariaDB is safe only with the read-only guard on: Running a local instance against the production MariaDB is safe only with the read-only guard on:
+66
View File
@@ -0,0 +1,66 @@
// WebSocket upgrade authentication (issue #38).
//
// Every connection is classified once, at the HTTP upgrade:
// browser — came through the trusted proxy with an Authelia identity in an allowed group;
// receives the live event feed.
// worker — presented the worker key at the handshake (Authorization: Bearer <key>).
// pending — neither, accepted only while WORKER_AUTH_ENFORCE is off so that workers
// which predate handshake auth can still identify with worker_connect.
// Gets no events and may send nothing but worker_connect.
// reject — refused with 401 before the upgrade completes.
const crypto = require('crypto');
const { ssoIdentity, ALLOWED_GROUPS } = require('./pageauth');
// Constant-time string comparison. Hashing first makes both sides the same
// length, so neither the content nor the length of the secret leaks via timing.
// An unset or empty secret never matches.
function safeEqual(given, secret) {
if (typeof given !== 'string' || typeof secret !== 'string' || !given || !secret) return false;
const a = crypto.createHash('sha256').update(given).digest();
const b = crypto.createHash('sha256').update(secret).digest();
return crypto.timingSafeEqual(a, b);
}
function checkWorkerKey(key, workerKey = process.env.WORKER_API_KEY) {
return safeEqual(key, workerKey);
}
function workerAuthEnforced(env = process.env) {
return env.WORKER_AUTH_ENFORCE === '1';
}
function bearerToken(req) {
const h = (req.headers && req.headers.authorization) || '';
const m = /^Bearer\s+(.+)$/i.exec(h);
return m ? m[1].trim() : null;
}
function classifyUpgrade(req, opts = {}) {
const workerKey = 'workerKey' in opts ? opts.workerKey : process.env.WORKER_API_KEY;
const enforce = 'enforce' in opts ? opts.enforce : workerAuthEnforced();
const token = bearerToken(req);
if (token !== null) {
// A wrong key is never downgraded to pending: it is either a misconfigured
// worker or an attacker, and both should see the refusal.
return checkWorkerKey(token, workerKey) ? 'worker' : 'reject';
}
const identity = opts.trusted ? ssoIdentity(req, opts.trusted) : ssoIdentity(req);
if (identity && identity.groups.some(g => ALLOWED_GROUPS.includes(g))) return 'browser';
return enforce ? 'reject' : 'pending';
}
// May this connection register as a worker with this worker_connect message?
function allowWorkerConnect(kind, apiKey, opts = {}) {
const workerKey = 'workerKey' in opts ? opts.workerKey : process.env.WORKER_API_KEY;
const enforce = 'enforce' in opts ? opts.enforce : workerAuthEnforced();
if (kind === 'worker') return { ok: true };
if (checkWorkerKey(apiKey, workerKey)) return { ok: true };
if (kind === 'pending' && !enforce && !apiKey) return { ok: true, legacy: true };
return { ok: false };
}
module.exports = { safeEqual, checkWorkerKey, workerAuthEnforced, bearerToken, classifyUpgrade, allowWorkerConnect };
+89 -20
View File
@@ -14,10 +14,24 @@ const { validateWebhookUrl, applyParams, evalCondition, calculateNextRun } = req
const { PAGES } = require('./lib/nav'); const { PAGES } = require('./lib/nav');
const { renderPage, renderError } = require('./lib/render'); const { renderPage, renderError } = require('./lib/render');
const { upsertUser, makeAuthenticatePage, ssoIdentity, trustedProxies } = require('./lib/pageauth'); const { upsertUser, makeAuthenticatePage, ssoIdentity, trustedProxies } = require('./lib/pageauth');
const { safeEqual, checkWorkerKey, workerAuthEnforced, classifyUpgrade, allowWorkerConnect } = require('./lib/wsauth');
const app = express(); const app = express();
const server = http.createServer(app); 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. // 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'; 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 // Send command to worker
workerWs.send(JSON.stringify({ sendCommandToWorker(workerWs, {
type: 'execute_command', type: 'execute_command',
execution_id: executionId, execution_id: executionId,
command: schedule.command, command: schedule.command,
worker_id: workerId, worker_id: workerId,
timeout: 5 * 60_000 // SCHEDULED_CMD_TIMEOUT timeout: 5 * 60_000 // SCHEDULED_CMD_TIMEOUT
})); });
broadcast({ type: 'execution_started', execution_id: executionId, workflow_id: null }); 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 workerClients = new Set(); // Worker agent connections
const workers = new Map(); // Map worker_id -> WebSocket connection const workers = new Map(); // Map worker_id -> WebSocket connection
wss.on('connection', (ws) => { // Which worker each in-flight command was sent to, keyed by command_id (workflow steps)
// Default to browser client until worker_connect identifies it as a worker // or execution_id (quick/scheduled/internal commands). Results from any other
browserClients.add(ws); // 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 // Handle incoming messages from workers
ws.on('message', async (data) => { ws.on('message', async (data) => {
try { try {
const message = JSON.parse(data.toString()); 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') { if (message.type === 'command_result') {
// Handle command result from worker // Handle command result from worker
const { execution_id, command_id, worker_id, success, stdout, stderr, duration, timestamp } = message; 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 // Add result to execution logs
await addExecutionLog(execution_id, { await addExecutionLog(execution_id, {
step: 'command_execution', step: 'command_execution',
@@ -496,13 +553,20 @@ wss.on('connection', (ws) => {
} }
if (message.type === 'worker_connect') { if (message.type === 'worker_connect') {
// Authenticate worker — reject if api_key is provided but wrong
const { worker_id, worker_name, api_key } = message; const { worker_id, worker_name, api_key } = message;
if (api_key && api_key !== process.env.WORKER_API_KEY) { if (ws.isWorker) return; // already identified; ignore repeats
console.warn(`[Security] Worker connection rejected: invalid API key from "${worker_name}"`); 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'); ws.close(4001, 'Unauthorized');
return; 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 // Move from browser set to worker set
browserClients.delete(ws); browserClients.delete(ws);
workerClients.add(ws); workerClients.add(ws);
@@ -551,8 +615,8 @@ wss.on('connection', (ws) => {
} }
if (message.type === 'pong') { if (message.type === 'pong') {
// Use the DB worker ID stored on connect; fall back to message payload // Only the DB worker ID bound at worker_connect; never a client-supplied id.
const dbId = ws.dbWorkerId || message.worker_id; const dbId = ws.dbWorkerId;
if (dbId) { if (dbId) {
await pool.query( await pool.query(
`UPDATE workers SET last_heartbeat=NOW() WHERE id=?`, `UPDATE workers SET last_heartbeat=NOW() WHERE id=?`,
@@ -567,6 +631,7 @@ wss.on('connection', (ws) => {
}); });
ws.on('close', () => { ws.on('close', () => {
clearTimeout(ws.identifyTimer);
browserClients.delete(ws); browserClients.delete(ws);
workerClients.delete(ws); workerClients.delete(ws);
if (ws.workerId) { if (ws.workerId) {
@@ -721,7 +786,7 @@ async function authenticateSSO(req, res, next) {
// Gandalf machine-to-machine API key auth // Gandalf machine-to-machine API key auth
function authenticateGandalf(req, res, next) { function authenticateGandalf(req, res, next) {
const apiKey = req.headers['x-gandalf-api-key']; 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' }); return res.status(401).json({ error: 'Unauthorized' });
} }
req.user = { username: 'gandalf:link_stats', isAdmin: false }; 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) ? Math.min(Math.max(parseInt(step.timeout, 10) * 1000, 5000), 600000)
: COMMAND_TIMEOUT_MS; : COMMAND_TIMEOUT_MS;
workerWs.send(JSON.stringify({ sendCommandToWorker(workerWs, {
type: 'execute_command', type: 'execute_command',
execution_id: executionId, execution_id: executionId,
command_id: commandId, command_id: commandId,
command: command, command: command,
worker_id: workerId, worker_id: workerId,
timeout: stepTimeoutMs timeout: stepTimeoutMs
})); });
// Per-step retry: step.retries (default 0) with step.retryDelayMs (default 2000) // Per-step retry: step.retries (default 0) with step.retryDelayMs (default 2000)
const maxRetries = Math.min(parseInt(step.retries || 0, 10), 5); 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, step: stepNumber, action: 'command_sent', worker_id: workerId,
command: command, command_id: retryCommandId, timestamp: new Date().toISOString() command: command, command_id: retryCommandId, timestamp: new Date().toISOString()
}); });
workerWs.send(JSON.stringify({ sendCommandToWorker(workerWs, {
type: 'execute_command', execution_id: executionId, command_id: retryCommandId, type: 'execute_command', execution_id: executionId, command_id: retryCommandId,
command: command, worker_id: workerId, timeout: stepTimeoutMs command: command, worker_id: workerId, timeout: stepTimeoutMs
})); });
commandId = retryCommandId; // update for next waitForCommandResult call commandId = retryCommandId; // update for next waitForCommandResult call
} }
results.push(result); results.push(result);
@@ -1258,7 +1323,7 @@ app.post('/api/workers/heartbeat', async (req, res) => {
const apiKey = req.headers['x-api-key']; const apiKey = req.headers['x-api-key'];
// Verify API key — reject missing or wrong keys // 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' }); 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', type: 'execute_command',
execution_id: executionId, execution_id: executionId,
command: command, command: command,
worker_id: worker_id, worker_id: worker_id,
timeout: QUICK_CMD_TIMEOUT_MS timeout: QUICK_CMD_TIMEOUT_MS
})); });
res.json({ execution_id: executionId }); res.json({ execution_id: executionId });
} catch (error) { } 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' }); 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}`); console.log(`Command sent to worker ${workerId}: ${command}`);
broadcast({ type: 'execution_started', execution_id: executionId, workflow_id: null }); 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.'); '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'}`); 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) { if (DEV_READONLY) {
console.warn('************************************************************'); console.warn('************************************************************');
console.warn('* PULSE_DEV_READONLY IS ON — background jobs are disabled *'); console.warn('* PULSE_DEV_READONLY IS ON — background jobs are disabled *');
+107
View File
@@ -0,0 +1,107 @@
'use strict';
const { parseTrustedProxies } = require('../lib/pageauth');
const { safeEqual, checkWorkerKey, bearerToken, classifyUpgrade, allowWorkerConnect } = require('../lib/wsauth');
const PROXY = '192.0.2.10';
const KEY = 'worker-secret-key';
const trusted = parseTrustedProxies(PROXY);
function req(remoteAddress, headers = {}) {
return { headers: { ...headers }, socket: { remoteAddress } };
}
const sso = (groups) => ({ 'remote-user': 'alice', 'remote-groups': groups });
beforeEach(() => { jest.spyOn(console, 'warn').mockImplementation(() => {}); });
afterEach(() => jest.restoreAllMocks());
describe('safeEqual / checkWorkerKey', () => {
test('matches only the exact secret', () => {
expect(safeEqual(KEY, KEY)).toBe(true);
expect(safeEqual(`${KEY}x`, KEY)).toBe(false);
expect(safeEqual('short', KEY)).toBe(false);
});
test('an unset or empty secret never matches', () => {
expect(checkWorkerKey('', '')).toBe(false);
expect(checkWorkerKey(undefined, undefined)).toBe(false);
expect(checkWorkerKey('anything', undefined)).toBe(false);
});
test('non-string input is rejected', () => {
expect(safeEqual(['a'], KEY)).toBe(false);
expect(safeEqual(null, KEY)).toBe(false);
});
});
describe('bearerToken', () => {
test('parses the Authorization header', () => {
expect(bearerToken(req('x', { authorization: `Bearer ${KEY}` }))).toBe(KEY);
expect(bearerToken(req('x', { authorization: `bearer ${KEY} ` }))).toBe(KEY);
expect(bearerToken(req('x', { authorization: 'Basic abc' }))).toBeNull();
expect(bearerToken(req('x'))).toBeNull();
});
});
describe('classifyUpgrade', () => {
const opts = (enforce) => ({ trusted, workerKey: KEY, enforce });
test('trusted proxy with an allowed group is a browser', () => {
expect(classifyUpgrade(req(PROXY, sso('employee')), opts(true))).toBe('browser');
});
test('trusted proxy with a wrong group is not a browser', () => {
expect(classifyUpgrade(req(PROXY, sso('guests')), opts(true))).toBe('reject');
expect(classifyUpgrade(req(PROXY, sso('guests')), opts(false))).toBe('pending');
});
test('identity headers from an untrusted host do not make a browser', () => {
expect(classifyUpgrade(req('192.0.2.99', sso('admin')), opts(true))).toBe('reject');
expect(classifyUpgrade(req('192.0.2.99', sso('admin')), opts(false))).toBe('pending');
});
test('correct Bearer key is a worker from any host', () => {
expect(classifyUpgrade(req('192.0.2.99', { authorization: `Bearer ${KEY}` }), opts(true))).toBe('worker');
});
test('wrong Bearer key is rejected even while not enforced', () => {
expect(classifyUpgrade(req('192.0.2.99', { authorization: 'Bearer nope' }), opts(false))).toBe('reject');
});
test('no credentials: pending while not enforced, rejected once enforced', () => {
expect(classifyUpgrade(req('192.0.2.99'), opts(false))).toBe('pending');
expect(classifyUpgrade(req('192.0.2.99'), opts(true))).toBe('reject');
});
test('with WORKER_API_KEY unset no Bearer token is accepted', () => {
const o = { trusted, workerKey: undefined, enforce: true };
expect(classifyUpgrade(req('192.0.2.99', { authorization: 'Bearer ' }), o)).toBe('reject');
expect(classifyUpgrade(req('192.0.2.99', { authorization: 'Bearer undefined' }), o)).toBe('reject');
});
});
describe('allowWorkerConnect', () => {
const o = (enforce) => ({ workerKey: KEY, enforce });
test('a handshake-authenticated worker may register', () => {
expect(allowWorkerConnect('worker', undefined, o(true))).toEqual({ ok: true });
});
test('a pending connection with the right api_key may register', () => {
expect(allowWorkerConnect('pending', KEY, o(true))).toEqual({ ok: true });
});
test('a pending connection with a wrong api_key is refused', () => {
expect(allowWorkerConnect('pending', 'nope', o(false))).toEqual({ ok: false });
});
test('keyless worker: allowed as legacy while not enforced, refused once enforced', () => {
expect(allowWorkerConnect('pending', undefined, o(false))).toEqual({ ok: true, legacy: true });
expect(allowWorkerConnect('pending', undefined, o(true))).toEqual({ ok: false });
});
test('a browser session cannot turn itself into a worker without the key', () => {
expect(allowWorkerConnect('browser', undefined, o(false))).toEqual({ ok: false });
expect(allowWorkerConnect('browser', KEY, o(false))).toEqual({ ok: true });
});
});
+5 -2
View File
@@ -90,7 +90,9 @@ class PulseWorker {
connectWebSocket() { connectWebSocket() {
console.log(`[PULSE Worker] Connecting to WebSocket...`); console.log(`[PULSE Worker] Connecting to WebSocket...`);
this.ws = new WebSocket(this.wsUrl); // The server authenticates the WebSocket upgrade with the worker key (issue #38).
const headers = this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {};
this.ws = new WebSocket(this.wsUrl, { headers });
this.ws.on('open', () => { this.ws.on('open', () => {
console.log('[PULSE Worker] WebSocket connected'); console.log('[PULSE Worker] WebSocket connected');
@@ -98,7 +100,8 @@ class PulseWorker {
this.ws.send(JSON.stringify({ this.ws.send(JSON.stringify({
type: 'worker_connect', type: 'worker_connect',
worker_id: this.workerId, worker_id: this.workerId,
worker_name: this.workerName worker_name: this.workerName,
api_key: this.apiKey
})); }));
}); });