Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a6a4c0b66 | ||
|
|
6ffe230c34 | ||
|
|
7a01c28e06 | ||
|
|
61991841aa | ||
|
|
f140b380fb | ||
|
|
93b1422300 | ||
|
|
6d289a3bce |
No files matched your search
@@ -3,9 +3,12 @@ name: CI
|
||||
# One pipeline: lint, unit tests, audit, scans, integration and UI tests must all pass before main deploys (#45).
|
||||
# Actions are pinned to full commit SHAs (version in the trailing comment).
|
||||
|
||||
# Pushes build only main (which deploys); branches are built through their pull
|
||||
# request. Building both pushes and pull requests of a branch ran every job twice and
|
||||
# doubled the runner queue.
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: ["**"]
|
||||
schedule:
|
||||
|
||||
@@ -596,9 +596,10 @@ Everything runs from `.gitea/workflows/ci.yml`:
|
||||
| `Deploy` | Calls the `pulse-deploy` webhook on CT 122, waits until `/healthz` reports the tested commit, then tags it `deploy-*` | Push to `main`, only after all six checks pass |
|
||||
| `Notify` | Matrix alert on any failure on `main` or in the weekly audit, and on every deploy | As needed |
|
||||
|
||||
Branch protection on `main` requires `CI / Lint (eslint) (push)`, `CI / Test (jest) (push)`,
|
||||
`CI / Security (npm audit) (push)`, `CI / Scan (secrets, workflows, shell) (push)`,
|
||||
`CI / Integration (api) (push)` and `CI / UI (playwright) (push)`. Actions are pinned to commit
|
||||
Branch protection on `main` requires `CI / Lint (eslint) (pull_request)`, `CI / Test (jest) (pull_request)`,
|
||||
`CI / Security (npm audit) (pull_request)`, `CI / Scan (secrets, workflows, shell) (pull_request)`,
|
||||
`CI / Integration (api) (pull_request)` and `CI / UI (playwright) (pull_request)` (branches are only
|
||||
built through their pull request; pushes build `main`). Actions are pinned to commit
|
||||
SHAs, container images to digests, checkouts don't keep the token, and builds use `npm ci`. The plan for the rest of the pipeline is tracked in #45.
|
||||
|
||||
### Integration tests
|
||||
|
||||
@@ -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
@@ -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; } },
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
+14
-2
@@ -6,8 +6,20 @@
|
||||
set -euo pipefail
|
||||
: "${DB_NAME:?}" "${DB_USER:?}" "${DB_PASSWORD:?}"
|
||||
|
||||
apt-get update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends mariadb-server >/dev/null
|
||||
# The Playwright image points apt at Azure's Ubuntu mirror, which our runner can't
|
||||
# always reach; use the main Ubuntu mirror instead, and retry transient failures.
|
||||
for f in /etc/apt/sources.list /etc/apt/sources.list.d/*.list /etc/apt/sources.list.d/*.sources; do
|
||||
[ -f "$f" ] && sed -i 's#http://azure\.archive\.ubuntu\.com/#http://archive.ubuntu.com/#g' "$f"
|
||||
done
|
||||
for attempt in 1 2 3; do
|
||||
if apt-get -o Acquire::Retries=3 update -qq \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=3 install -y -qq --no-install-recommends mariadb-server >/dev/null; then
|
||||
break
|
||||
fi
|
||||
[ "$attempt" = 3 ] && { echo "::error::could not install mariadb-server"; exit 1; }
|
||||
echo "apt failed (attempt $attempt); retrying in 10s"
|
||||
sleep 10
|
||||
done
|
||||
mkdir -p /run/mysqld && chown mysql:mysql /run/mysqld
|
||||
if ! mariadb-admin ping --silent 2>/dev/null; then
|
||||
(mariadbd --user=mysql --bind-address=127.0.0.1 --port=3306 >/tmp/mariadb.log 2>&1 &)
|
||||
|
||||
@@ -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' }
|
||||
|
||||
@@ -18,11 +18,22 @@ const SSO = {
|
||||
};
|
||||
|
||||
async function api(method, url, { headers = {}, body } = {}) {
|
||||
const res = await fetch(BASE + url, {
|
||||
const send = () => fetch(BASE + url, {
|
||||
method,
|
||||
headers: { ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...headers },
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
let res;
|
||||
try {
|
||||
res = await send();
|
||||
} catch (e) {
|
||||
// A pooled keep-alive connection can be closed by the server (5 s idle timeout) just
|
||||
// as the client reuses it: ECONNRESET. Retry once, but only reads; a write might
|
||||
// already have taken effect.
|
||||
const reset = e && e.cause && e.cause.code === 'ECONNRESET';
|
||||
if (method !== 'GET' || !reset) throw e;
|
||||
res = await send();
|
||||
}
|
||||
const text = await res.text();
|
||||
let json = null;
|
||||
try { json = JSON.parse(text); } catch { /* not JSON */ }
|
||||
|
||||
@@ -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));
|
||||
});
|
||||
+5
-2
@@ -123,10 +123,13 @@ describe('evalCondition', () => {
|
||||
|
||||
describe('calculateNextRun', () => {
|
||||
test('interval: returns a date ~N minutes in the future', () => {
|
||||
// Bounded by the clock before and after the call: its first use loads cron-parser,
|
||||
// which took 30 s once on a loaded CI runner and broke a fixed 1 s tolerance.
|
||||
const before = Date.now();
|
||||
const result = calculateNextRun('interval', '30');
|
||||
expect(result.getTime()).toBeGreaterThanOrEqual(before + 30 * 60000 - 100);
|
||||
expect(result.getTime()).toBeLessThanOrEqual(before + 30 * 60000 + 1000);
|
||||
const after = Date.now();
|
||||
expect(result.getTime()).toBeGreaterThanOrEqual(before + 30 * 60000);
|
||||
expect(result.getTime()).toBeLessThanOrEqual(after + 30 * 60000);
|
||||
});
|
||||
|
||||
test('interval: throws on non-positive value', () => {
|
||||
|
||||
Reference in new issue
Block a user