Rate limits per user, and coalesce live-event reloads #70

Merged
jared merged 1 commits from rate-limits into main 2026-11-23 11:34:16 -05:00
7 changed files with 98 additions and 9 deletions

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
'use strict';
// Rate-limit buckets (#10). Everyone reaches Pulse through the same reverse proxy, so
// keying on the client IP put every user in one shared bucket, which the live UI alone
// could empty. Instead:
// - a trusted SSO identity gets its own bucket (user:<name>);
// - Gandalf, proven by a VALID key, gets one (a forged header must not let anyone
// drain Gandalf's bucket, so an invalid key falls back to the IP);
// - everything else is keyed by IP, as before.
const { ipKeyGenerator } = require('express-rate-limit');
const { ssoIdentity } = require('./pageauth');
const { safeEqual } = require('./wsauth');
function rateLimitKey(req, env = process.env) {
const who = ssoIdentity(req);
if (who && who.username) return `user:${who.username}`;
const gandalfKey = req.headers && req.headers['x-gandalf-api-key'];
if (gandalfKey && env.GANDALF_API_KEY && safeEqual(gandalfKey, env.GANDALF_API_KEY)) return 'gandalf';
return `ip:${ipKeyGenerator(req.ip || (req.socket && req.socket.remoteAddress) || '')}`;
}
module.exports = { rateLimitKey };
+20 -1
View File
@@ -633,6 +633,25 @@
} catch (e) { err('autoRefresh start failed', e); }
}
/**
* Run fn at most once per `ms`: at once when idle, otherwise once at the end of the
* window (so the last event is never lost). Live events can arrive several times a
* second; reloading on each one used up the API rate limit (#10).
*/
function throttle(fn, ms) {
let last = 0;
let timer = null;
return function throttled() {
const wait = last + ms - Date.now();
if (wait <= 0 && !timer) {
last = Date.now();
fn();
} else if (!timer) {
timer = setTimeout(() => { timer = null; last = Date.now(); fn(); }, Math.max(wait, 0));
}
};
}
/* -------------------------------------------------------------------
9. Public surface
------------------------------------------------------------------- */
@@ -654,7 +673,7 @@
get beep() { return LT().beep; },
esc: esc,
fmt: fmt,
util: { download: download, storage: storage },
util: { download: download, storage: storage, throttle: throttle },
/** Escape hatch for pages that need to push a frame upstream. */
ws: { send(d) { return _wsHandle && _wsHandle.send ? _wsHandle.send(d) : false; }, get handle() { return _wsHandle; } },
+10 -2
View File
@@ -205,15 +205,23 @@
return refresh();
}
// Live events come in bursts; reload at most once per 2 s each (#10).
const reloadWorkers = Pulse.util.throttle(() => {
Promise.all([loadWorkers(), loadRunningCount()]).then(([workers, rt]) => renderStats(workers, rt));
}, 2000);
const reloadExecutions = Pulse.util.throttle(() => {
Promise.all([loadExecutions(), loadRunningCount()]).then(([, rt]) => renderStats(_workers, rt));
}, 2000);
function onEvent(type) {
if (type === 'worker_update') {
Promise.all([loadWorkers(), loadRunningCount()]).then(([workers, rt]) => renderStats(workers, rt));
reloadWorkers();
return true;
}
if (type === 'execution_started' || type === 'execution_status' ||
type === 'command_result' || type === 'workflow_result' ||
type === 'executions_bulk_deleted') {
Promise.all([loadExecutions(), loadRunningCount()]).then(([, rt]) => renderStats(_workers, rt));
reloadExecutions();
return true;
}
return false;
+6 -4
View File
@@ -100,10 +100,12 @@
}
}
async function reloadCurrent() {
async function reloadNow() {
await loadView(state.view, false);
render();
}
// Live events trigger this; coalesce bursts into at most one reload per 2 s (#10).
const reloadCurrent = Pulse.util.throttle(reloadNow, 2000);
/* ------------------------------------------------------------------
Rendering: list
@@ -694,7 +696,7 @@
toast('error', (e && e.message) || 'Failed to delete executions');
return;
}
await reloadCurrent();
await reloadNow();
},
'ex:abort': async (el) => {
@@ -716,7 +718,7 @@
toast('error', (e && e.message) || 'Failed to abort execution');
return;
}
await reloadCurrent();
await reloadNow();
},
/* Frozen cross-page contract: quick.js consumes and clears pulse_rerun. */
@@ -771,7 +773,7 @@
return;
}
await openDetail(id, true);
await reloadCurrent();
await reloadNow();
},
};
+4 -1
View File
@@ -258,9 +258,12 @@
return loadWorkers();
}
// Heartbeats from many workers arrive in bursts; reload at most once per 2 s (#10).
const reloadWorkers = Pulse.util.throttle(() => { loadWorkers(); }, 2000);
function onEvent(type) {
if (type === 'worker_update') {
loadWorkers();
reloadWorkers();
return true;
}
return false;
+5 -1
View File
@@ -4,6 +4,7 @@ const WebSocket = require('ws');
const mysql = require('mysql2/promise');
const crypto = require('crypto');
const rateLimit = require('express-rate-limit');
const { rateLimitKey } = require('./lib/ratelimit');
const path = require('path');
const fs = require('fs');
const helmet = require('helmet');
@@ -81,9 +82,11 @@ const limitFromEnv = (name, fallback) => {
const n = parseInt(process.env[name], 10);
return Number.isInteger(n) && n > 0 ? n : fallback;
};
// Each signed-in user, and Gandalf, gets its own bucket (lib/ratelimit.js, #10).
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: limitFromEnv('PULSE_API_RATE_MAX', 300),
max: limitFromEnv('PULSE_API_RATE_MAX', 1000),
keyGenerator: rateLimitKey,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many requests, please try again later' }
@@ -91,6 +94,7 @@ const apiLimiter = rateLimit({
const executionLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: limitFromEnv('PULSE_EXEC_RATE_MAX', 20),
keyGenerator: rateLimitKey,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many execution requests, please slow down' }
+31
View File
@@ -0,0 +1,31 @@
'use strict';
process.env.TRUSTED_PROXIES = '192.0.2.10';
const { rateLimitKey } = require('../lib/ratelimit');
const PROXY = '192.0.2.10';
const req = (remoteAddress, headers = {}) => ({ headers, ip: remoteAddress, socket: { remoteAddress } });
const env = { GANDALF_API_KEY: 'g-key' };
beforeAll(() => jest.spyOn(console, 'warn').mockImplementation(() => {}));
afterAll(() => jest.restoreAllMocks());
test('each signed-in user behind the proxy gets their own bucket', () => {
expect(rateLimitKey(req(PROXY, { 'remote-user': 'alice' }), env)).toBe('user:alice');
expect(rateLimitKey(req(PROXY, { 'remote-user': 'bob' }), env)).toBe('user:bob');
});
test('identity headers from anywhere but the proxy are ignored (keyed by IP)', () => {
expect(rateLimitKey(req('198.51.100.7', { 'remote-user': 'alice' }), env)).toBe('ip:198.51.100.7');
});
test('Gandalf gets its own bucket only with the valid key', () => {
expect(rateLimitKey(req('10.10.10.61', { 'x-gandalf-api-key': 'g-key' }), env)).toBe('gandalf');
expect(rateLimitKey(req('10.10.10.61', { 'x-gandalf-api-key': 'wrong' }), env)).toBe('ip:10.10.10.61');
expect(rateLimitKey(req('10.10.10.61', { 'x-gandalf-api-key': 'g-key' }), {})).toBe('ip:10.10.10.61');
});
test('anything else is keyed by IP (IPv6 grouped by subnet)', () => {
expect(rateLimitKey(req('10.10.10.8'), env)).toBe('ip:10.10.10.8');
expect(rateLimitKey(req('2001:db8::1'), env)).toBe(rateLimitKey(req('2001:db8::2'), env));
});