Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,726 @@
|
||||
"use strict";
|
||||
|
||||
// adpanel:progress-poll-budget — pins for the dedicated progress-poll budget
|
||||
// and the 429 backoff in the settings.js pollers.
|
||||
//
|
||||
// Constraint under test: the three UI progress pollers —
|
||||
// GET /api/settings/database/install-progress/:jobId (2s interval),
|
||||
// GET /api/settings/servers/:name/transfer (1.5s interval),
|
||||
// GET /api/admin/nodes/:id/stats (5s interval),
|
||||
// — are generic /api budget consumers. While any generic budget enforces
|
||||
// (the Redis-backed global limiter or the app-wide in-memory fallback), a
|
||||
// couple of concurrent installs/transfers/node-stats views eat the per-IP
|
||||
// window and every OTHER /api call starts 429ing — and the install poller
|
||||
// then marks its own RUNNING install failed on the very 429 its polling
|
||||
// caused. The fix has two halves, both locked here:
|
||||
// 1. The three endpoint families are exempt from BOTH generic budgets via
|
||||
// the ONE shared isRateLimitExempt helper (RATE_LIMIT_EXEMPT_PATTERNS +
|
||||
// the owner's skip calling it) and are instead budgeted by a DEDICATED
|
||||
// express-rate-limit instance: own buildSharedRateLimitRedisStore store
|
||||
// instance, distinct "progress-poll:" prefix, windowMs 60s, max 240,
|
||||
// keyed per /56-bucketed IP + session user, coupled to the same optional
|
||||
// global-brake flag (security.rate_limiting) — never enforcing while the
|
||||
// global brake is disabled, never double-budgeting.
|
||||
// 2. The settings.js install pollers treat HTTP 429 as backoff-not-failure:
|
||||
// 429 does NOT consume the consecutivePollFailures budget (which exists
|
||||
// for gateway blips), the next poll honors a numeric Retry-After header
|
||||
// (clamped 2-15s, else 5s), a bounded consecutive-429 counter keeps a
|
||||
// permanently-throttled panel from polling forever, and the 404 /
|
||||
// non-429 failure semantics are preserved exactly.
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
const express = require("express");
|
||||
const { rateLimit, ipKeyGenerator } = require("express-rate-limit");
|
||||
const { RedisStore: RateLimitRedisStore } = require("rate-limit-redis");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const INDEX_JS = path.join(ROOT, "index.js");
|
||||
const OWNER_JS = path.join(ROOT, "services", "global-rate-limit-owner.js");
|
||||
const SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js");
|
||||
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
||||
const ownerSource = fs.readFileSync(OWNER_JS, "utf8");
|
||||
const settingsSource = fs.readFileSync(SETTINGS_JS, "utf8");
|
||||
|
||||
function countOccurrences(haystack, needle) {
|
||||
return haystack.split(needle).length - 1;
|
||||
}
|
||||
|
||||
function indexOfOrThrow(source, needle) {
|
||||
const idx = source.indexOf(needle);
|
||||
assert.ok(idx >= 0, `expected source pin not found: ${needle}`);
|
||||
return idx;
|
||||
}
|
||||
|
||||
// Brace-balanced extraction (comment/string aware) of the object literal that
|
||||
// follows `rateLimit(` in a const definition — evaluates the SHIPPED options,
|
||||
// not a re-typed copy.
|
||||
function extractLimiterOptions(source, anchor) {
|
||||
const start = indexOfOrThrow(source, anchor);
|
||||
const open = source.indexOf("{", start);
|
||||
assert.ok(open > start, `no options object after ${anchor}`);
|
||||
let depth = 0;
|
||||
let inLine = false;
|
||||
let inBlock = false;
|
||||
let quote = null;
|
||||
for (let i = open; i < source.length; i++) {
|
||||
const c = source[i];
|
||||
const n = source[i + 1];
|
||||
if (inLine) { if (c === "\n") inLine = false; continue; }
|
||||
if (inBlock) { if (c === "*" && n === "/") { inBlock = false; i++; } continue; }
|
||||
if (quote) { if (c === "\\") { i++; continue; } if (c === quote) quote = null; continue; }
|
||||
if (c === "/" && n === "/") { inLine = true; i++; continue; }
|
||||
if (c === "/" && n === "*") { inBlock = true; i++; continue; }
|
||||
if (c === "'" || c === '"' || c === "`") { quote = c; continue; }
|
||||
if (c === "{") depth++;
|
||||
else if (c === "}") {
|
||||
depth--;
|
||||
if (depth === 0) return source.slice(open, i + 1);
|
||||
}
|
||||
}
|
||||
throw new Error(`unbalanced braces while extracting ${anchor}`);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 1. Source pins — the dedicated limiter, its budget arithmetic, its store
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("the three poll routes mount the dedicated progressPollRateLimiter", () => {
|
||||
for (const marker of [
|
||||
'app.get("/api/settings/database/install-progress/:jobId", progressPollRateLimiter,',
|
||||
'app.get("/api/admin/nodes/:id/stats", progressPollRateLimiter,',
|
||||
'app.get("/api/settings/servers/:name/transfer", progressPollRateLimiter,',
|
||||
]) {
|
||||
assert.ok(indexSource.includes(marker), `missing dedicated-limiter mount: ${marker}`);
|
||||
}
|
||||
assert.equal(countOccurrences(indexSource, "progressPollRateLimiter,"), 3, "exactly the three poll routes carry the brake");
|
||||
});
|
||||
|
||||
test("the poll limiter is a 240/60s budget on its own store instance + distinct prefix, keyed ip+user", () => {
|
||||
const options = extractLimiterOptions(indexSource, "const progressPollRateLimiter = rateLimit(");
|
||||
assert.ok(options.includes("windowMs: 60 * 1000,"), "windowMs 60s");
|
||||
assert.ok(options.includes("max: 240,"), "max 240 per window");
|
||||
assert.ok(options.includes('buildSharedRateLimitRedisStore("progress-poll:", 60 * 1000)'), "own store instance via the shared factory with the DISTINCT progress-poll: prefix (one store instance per limiter)");
|
||||
assert.ok(options.includes("passOnStoreError: true"), "store errors fail open — abuse brake, not an auth control");
|
||||
assert.ok(options.includes("`progress-poll:${ipKeyGenerator(String(getRequestIp(req) || \"unknown\"))}:${req.session?.user || 'anon'}`"), "keyed per /56-bucketed IP + session user (the status-limiter wrapping shape)");
|
||||
assert.ok(options.includes("standardHeaders: true") && options.includes("legacyHeaders: false"), "standard headers so the 429 carries Retry-After for the pollers' backoff");
|
||||
// Coupled to the same optional global-brake flag: never enforce while the
|
||||
// global brake is disabled.
|
||||
assert.ok(options.includes("if (!security || security.rate_limiting !== true) return true;"), "skip when the global brake is off");
|
||||
// The trusted-subnet bypass consumer set is unchanged: this new limiter does
|
||||
// not consult network position.
|
||||
assert.ok(!options.includes("isRequestFromTrustedSubnet"), "the poll budget is not wired to the trusted-subnet bypass");
|
||||
});
|
||||
|
||||
test("the budget arithmetic is documented (2s/1.5s/5s pollers, 240/60s headroom)", () => {
|
||||
const anchor = indexOfOrThrow(indexSource, "// adpanel:progress-poll-budget — dedicated budget for the three UI progress");
|
||||
const comment = indexSource.slice(anchor, indexOfOrThrow(indexSource, "const progressPollRateLimiter = rateLimit("));
|
||||
for (const fragment of ["2s", "1.5s", "5s", "240", "60s", "4-6 concurrent viewers", "progress-poll:"]) {
|
||||
assert.ok(comment.includes(fragment), `the budget comment must document ${fragment}`);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 2. Exemption from the generic budgets — the ONE shared helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Extract the contiguous RATE_LIMIT_EXEMPT_PATHS/PATTERNS + isRateLimitExempt
|
||||
// block from index.js and evaluate it so the pins exercise the SHIPPED list.
|
||||
function extractExemptHelper() {
|
||||
const start = indexOfOrThrow(indexSource, "const RATE_LIMIT_EXEMPT_PATHS = new Set([");
|
||||
const fnStart = indexOfOrThrow(indexSource, "function isRateLimitExempt(path, method) {");
|
||||
assert.ok(fnStart > start, "the helper follows the lists");
|
||||
let depth = 0;
|
||||
let inLine = false;
|
||||
let inBlock = false;
|
||||
let quote = null;
|
||||
let openFound = false;
|
||||
for (let i = fnStart; i < indexSource.length; i++) {
|
||||
const c = indexSource[i];
|
||||
const n = indexSource[i + 1];
|
||||
if (inLine) { if (c === "\n") inLine = false; continue; }
|
||||
if (inBlock) { if (c === "*" && n === "/") { inBlock = false; i++; } continue; }
|
||||
if (quote) { if (c === "\\") { i++; continue; } if (c === quote) quote = null; continue; }
|
||||
if (c === "/" && n === "/") { inLine = true; i++; continue; }
|
||||
if (c === "/" && n === "*") { inBlock = true; i++; continue; }
|
||||
if (c === "'" || c === '"' || c === "`") { quote = c; continue; }
|
||||
if (c === "{") { depth++; openFound = true; }
|
||||
else if (c === "}") {
|
||||
depth--;
|
||||
if (openFound && depth === 0) {
|
||||
return vm.runInContext(indexSource.slice(start, i + 1) + "\nisRateLimitExempt;", vm.createContext({ Set, RegExp }));
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error("unbalanced braces while extracting isRateLimitExempt");
|
||||
}
|
||||
|
||||
const isRateLimitExempt = extractExemptHelper();
|
||||
|
||||
test("the three poll endpoint families are exempt from the generic budgets via the shared helper", () => {
|
||||
// The exact families the dedicated limiter budgets (parametric routes with
|
||||
// concrete values, and a hostile lookalike for each).
|
||||
for (const p of [
|
||||
"/api/settings/database/install-progress/mongodb-abc123",
|
||||
"/api/settings/servers/my%20server/transfer",
|
||||
"/api/admin/nodes/node-9/stats",
|
||||
]) {
|
||||
assert.equal(isRateLimitExempt(p, "GET"), true, `${p} must be exempt from the generic budgets (budgeted by progressPollRateLimiter instead)`);
|
||||
}
|
||||
// adpanel:progress-poll-budget — the transfer exemption is GET-only: the
|
||||
// disruptive POST transfer-initiation route keeps its generic per-IP budget
|
||||
// on top of its dedicated serverTransferRateLimiter, and a method-less
|
||||
// consult (legacy one-arg callers) must fail closed rather than exempt.
|
||||
assert.equal(isRateLimitExempt("/api/settings/servers/x/transfer", "POST"), false, "the disruptive POST transfer initiation keeps its generic per-IP budget");
|
||||
assert.equal(isRateLimitExempt("/api/settings/servers/x/transfer"), false, "a method-less consult must not exempt the transfer family (fail closed)");
|
||||
// No over-broad patterns: siblings and sub-paths stay budgeted.
|
||||
for (const p of [
|
||||
"/api/settings/database/install-progress/mongodb-abc123/extra",
|
||||
"/api/settings/database/install-progress/",
|
||||
"/api/settings/servers/x/transfers",
|
||||
"/api/settings/servers/x/transfer/history",
|
||||
"/api/admin/nodes/x/stats/history",
|
||||
"/api/settings/security",
|
||||
"/api/settings/servers",
|
||||
]) {
|
||||
assert.equal(isRateLimitExempt(p), false, `${p} must NOT be exempt`);
|
||||
}
|
||||
// The pre-existing exemptions survive untouched.
|
||||
for (const p of ["/api/me", "/health", "/api/servers/statuses", "/api/server/foo/status", "/api/server/foo/node-status"]) {
|
||||
assert.equal(isRateLimitExempt(p), true, `${p} keeps its existing exemption`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the owner's skip delegates to the ONE exempt helper (no duplicated inline list)", () => {
|
||||
assert.ok(ownerSource.includes("if (isRateLimitExempt(path, req.method)) return true;"), "the owner skip consults the shared helper with the original path and method");
|
||||
// The old inline duplication is gone from the owner.
|
||||
assert.ok(!ownerSource.includes('path === "/api/me"'), "no inline /api/me compare in the owner — the helper is the single source");
|
||||
// And index.js's generic list is the only inline enumeration.
|
||||
assert.equal(countOccurrences(indexSource, 'if (path === "/api/me") return true;'), 0, "the global limiter's inline exempt duplication is gone");
|
||||
});
|
||||
|
||||
test("the app-wide in-memory fallback skips the poll endpoints too (never double-budgeted)", () => {
|
||||
// Extract rateLimiterMiddleware verbatim (same technique as
|
||||
// tests/limiter-ipv6-bucketing.test.js) and run it with the REAL exempt
|
||||
// helper above, in fallback mode (Redis limiter not mounted).
|
||||
const fnStart = indexOfOrThrow(indexSource, "function rateLimiterMiddleware(req, res, next) {");
|
||||
let depth = 0;
|
||||
let open = indexSource.indexOf("{", fnStart);
|
||||
let inLine = false;
|
||||
let inBlock = false;
|
||||
let quote = null;
|
||||
let end = -1;
|
||||
for (let i = open; i < indexSource.length; i++) {
|
||||
const c = indexSource[i];
|
||||
const n = indexSource[i + 1];
|
||||
if (inLine) { if (c === "\n") inLine = false; continue; }
|
||||
if (inBlock) { if (c === "*" && n === "/") { inBlock = false; i++; } continue; }
|
||||
if (quote) { if (c === "\\") { i++; continue; } if (c === quote) quote = null; continue; }
|
||||
if (c === "/" && n === "/") { inLine = true; i++; continue; }
|
||||
if (c === "/" && n === "*") { inBlock = true; i++; continue; }
|
||||
if (c === "'" || c === '"' || c === "`") { quote = c; continue; }
|
||||
if (c === "{") depth++;
|
||||
else if (c === "}") { depth--; if (depth === 0) { end = i + 1; break; } }
|
||||
}
|
||||
assert.ok(end > fnStart, "unbalanced rateLimiterMiddleware extraction");
|
||||
const fnSource = indexSource.slice(fnStart, end);
|
||||
const security = { rate_limiting: true, limit: 5, window_seconds: 120 };
|
||||
const rateRequests = new Map();
|
||||
const sandbox = {
|
||||
security,
|
||||
isRequestFromTrustedSubnet: () => false,
|
||||
redisApiLimiterMounted: false,
|
||||
redisClient: null,
|
||||
isRateLimitExempt,
|
||||
ipKeyGenerator,
|
||||
getRequestIp: (req) => req.headers["x-test-ip"] || "127.0.0.1",
|
||||
rateRequests,
|
||||
RATE_MAX_TRACKED_IPS: 50000,
|
||||
String, Date, Math, Number, parseInt,
|
||||
};
|
||||
const middleware = vm.runInContext(`(${fnSource})`, vm.createContext(sandbox));
|
||||
const makeRes = () => ({
|
||||
status(code) { this.statusCode = code; return this; },
|
||||
setHeader(k, v) { this.headers[k] = v; return this; },
|
||||
send(body) { this.body = body; return this; },
|
||||
statusCode: 0, headers: {}, body: null,
|
||||
});
|
||||
const run = (p) => {
|
||||
const req = { path: p, method: "GET", headers: { "x-test-ip": "10.9.9.9" } };
|
||||
const res = makeRes();
|
||||
let nexted = false;
|
||||
middleware(req, res, () => { nexted = true; });
|
||||
return { nexted, res };
|
||||
};
|
||||
// A poll endpoint passes through uncounted.
|
||||
const poll = run("/api/admin/nodes/node-1/stats");
|
||||
assert.equal(poll.nexted, true, "poll endpoints ride through the in-memory fallback untouched");
|
||||
assert.equal(rateRequests.size, 0, "no budget consumed");
|
||||
// A non-poll endpoint is counted.
|
||||
const other = run("/api/servers");
|
||||
assert.equal(other.nexted, true);
|
||||
assert.equal(rateRequests.size, 1, "generic endpoints still consume the fallback budget");
|
||||
// The dedicated limiter owns the poll budget; the fallback never does.
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 3. Dedicated limiter behavior — real express-rate-limit over the shipped
|
||||
// options, evaluated from the extracted source
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function createFakeRedis() {
|
||||
const data = new Map();
|
||||
let shaCounter = 0;
|
||||
const loadedShas = new Map();
|
||||
const sendCommand = async (...args) => {
|
||||
const cmd = args[0];
|
||||
if (cmd === "SCRIPT") {
|
||||
const script = args[2];
|
||||
let sha = loadedShas.get(script);
|
||||
if (!sha) { sha = `sha${++shaCounter}`; loadedShas.set(script, sha); }
|
||||
return sha;
|
||||
}
|
||||
if (cmd === "EVALSHA") {
|
||||
if (args.length >= 6) {
|
||||
const key = args[3];
|
||||
const resetOnChange = args[4] === "1";
|
||||
const windowMs = parseInt(args[5], 10);
|
||||
const now = Date.now();
|
||||
const entry = data.get(key);
|
||||
if (!entry || entry.exp <= now) { data.set(key, { hits: 1, exp: now + windowMs }); return [1, windowMs]; }
|
||||
entry.hits += 1;
|
||||
if (resetOnChange) { entry.exp = now + windowMs; return [entry.hits, windowMs]; }
|
||||
return [entry.hits, entry.exp - now];
|
||||
}
|
||||
const key = args[3];
|
||||
const entry = data.get(key);
|
||||
if (!entry || entry.exp <= Date.now()) return [0, -2];
|
||||
return [entry.hits, entry.exp - Date.now()];
|
||||
}
|
||||
throw new Error(`fake redis: unsupported command ${cmd}`);
|
||||
};
|
||||
return { sendCommand, data };
|
||||
}
|
||||
|
||||
function evaluateShippedPollLimiter(security) {
|
||||
const fake = createFakeRedis();
|
||||
const sandbox = {
|
||||
rateLimit,
|
||||
redisClient: { isReady: true }, // truthy → the shipped store expression builds the store
|
||||
buildSharedRateLimitRedisStore: (prefix, windowMs) => new RateLimitRedisStore({ prefix, sendCommand: fake.sendCommand }),
|
||||
ipKeyGenerator,
|
||||
getRequestIp: (req) => req.headers["x-test-ip"] || "127.0.0.1",
|
||||
security,
|
||||
};
|
||||
const options = extractLimiterOptions(indexSource, "const progressPollRateLimiter = rateLimit(");
|
||||
const middleware = vm.runInContext(`rateLimit(${options})`, vm.createContext(sandbox), { filename: "index.js[progressPollRateLimiter]" });
|
||||
return { middleware, fake };
|
||||
}
|
||||
|
||||
async function listen(app) {
|
||||
return new Promise((resolve) => {
|
||||
const server = app.listen(0, "127.0.0.1", () => resolve({ server, base: `http://127.0.0.1:${server.address().port}` }));
|
||||
});
|
||||
}
|
||||
|
||||
async function hit(base, p, headers) {
|
||||
const res = await fetch(base + p, { headers: headers || {} });
|
||||
let body = null;
|
||||
try { body = await res.json(); } catch { body = null; }
|
||||
return { status: res.status, body, headers: res.headers };
|
||||
}
|
||||
|
||||
test("the shipped poll limiter admits 2s polling and throttles abuse at its own 240/60s budget", async () => {
|
||||
const security = { rate_limiting: true, limit: 300, window_seconds: 120 };
|
||||
const { middleware, fake } = evaluateShippedPollLimiter(security);
|
||||
const app = express();
|
||||
app.use((req, res, next) => {
|
||||
if (req.headers["x-test-user"]) req.session = { user: req.headers["x-test-user"] };
|
||||
next();
|
||||
});
|
||||
app.get("/api/admin/nodes/:id/stats", middleware, (req, res) => res.json({ ok: true }));
|
||||
const { server, base } = await listen(app);
|
||||
try {
|
||||
// A legitimate viewer: 12/min at a 5s cadence — with headroom.
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const r = await hit(base, "/api/admin/nodes/n1/stats", { "x-test-ip": "10.1.1.1" });
|
||||
assert.equal(r.status, 200, `poll ${i + 1} within the dedicated budget`);
|
||||
}
|
||||
// Two full-blast install pollers (30/min each) plus a transfer poller
|
||||
// (40/min) plus the stats viewer stay under 240: 60 + 180 = 240 admitted.
|
||||
for (let i = 0; i < 180; i++) {
|
||||
const r = await hit(base, "/api/admin/nodes/n1/stats", { "x-test-ip": "10.1.1.1" });
|
||||
assert.equal(r.status, 200, `admitted poll ${60 + i + 1}`);
|
||||
}
|
||||
const blocked = await hit(base, "/api/admin/nodes/n1/stats", { "x-test-ip": "10.1.1.1" });
|
||||
assert.equal(blocked.status, 429, "the 241st poll in a minute is throttled by the DEDICATED budget");
|
||||
assert.ok(blocked.headers.get("retry-after"), "the 429 carries Retry-After for the poller backoff");
|
||||
assert.ok(blocked.body && blocked.body.error, "the 429 body is JSON the pollers can parse");
|
||||
|
||||
// Keyed per IP + session user: a different identity has its own budget.
|
||||
const otherUser = await hit(base, "/api/admin/nodes/n1/stats", { "x-test-ip": "10.1.1.1", "x-test-user": "other-admin" });
|
||||
assert.equal(otherUser.status, 200, "a different session user keys its own bucket");
|
||||
const otherIp = await hit(base, "/api/admin/nodes/n1/stats", { "x-test-ip": "10.2.2.2" });
|
||||
assert.equal(otherIp.status, 200, "a different IP keys its own bucket");
|
||||
|
||||
// Store isolation: only "progress-poll:" keys exist.
|
||||
for (const key of fake.data.keys()) {
|
||||
assert.ok(key.startsWith("progress-poll:"), `every counter lives under the distinct prefix (got ${key})`);
|
||||
}
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("the poll limiter is inert while the global brake is disabled (same optional system)", async () => {
|
||||
const security = { rate_limiting: false, limit: 300, window_seconds: 120 };
|
||||
const { middleware, fake } = evaluateShippedPollLimiter(security);
|
||||
const app = express();
|
||||
app.get("/api/admin/nodes/:id/stats", middleware, (req, res) => res.json({ ok: true }));
|
||||
const { server, base } = await listen(app);
|
||||
try {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const r = await hit(base, "/api/admin/nodes/n1/stats");
|
||||
assert.equal(r.status, 200);
|
||||
}
|
||||
assert.equal(fake.data.size, 0, "flag off → nothing enforces anywhere, no counters are written");
|
||||
// Flip the flag live: the shipped skip reads the security object.
|
||||
security.rate_limiting = true;
|
||||
const r = await hit(base, "/api/admin/nodes/n1/stats");
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(fake.data.size, 1, "flag on → the dedicated budget counts again");
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("settings transfer polls wait after a 429 without dropping the running job", async () => {
|
||||
const start = settingsSource.indexOf("async function fetchTransferJob(");
|
||||
const end = settingsSource.indexOf("async function loadTransferNodes(", start);
|
||||
assert.ok(start >= 0 && end > start);
|
||||
const progress = [];
|
||||
const cancelled = [];
|
||||
const runningJob = { status: "copying", finishedAt: null };
|
||||
let now = 1000;
|
||||
let requests = 0;
|
||||
let reloads = 0;
|
||||
const pollTransfer = vm.runInNewContext(`${settingsSource.slice(start, end)}\npollTransfer;`, {
|
||||
transferViewVersion: 1,
|
||||
transferPollTimer: 1,
|
||||
transferPollRetryAt: 0,
|
||||
Date: { now: () => now },
|
||||
fetch: async () => {
|
||||
requests += 1;
|
||||
if (requests === 1) return { ok: false, status: 429, headers: new Map([["retry-after", "20"]]) };
|
||||
return { ok: true, json: async () => ({ job: requests === 2 ? runningJob : null }) };
|
||||
},
|
||||
setTransferProgress: (job) => progress.push(job),
|
||||
clearInterval: (timer) => cancelled.push(timer),
|
||||
loadServers: () => { reloads += 1; },
|
||||
});
|
||||
|
||||
await pollTransfer("example", 1);
|
||||
now += 19000;
|
||||
await pollTransfer("example", 1);
|
||||
assert.equal(requests, 1);
|
||||
assert.deepEqual(cancelled, []);
|
||||
assert.equal(reloads, 0);
|
||||
|
||||
now += 1000;
|
||||
await pollTransfer("example", 1);
|
||||
assert.deepEqual(progress, [runningJob]);
|
||||
assert.deepEqual(cancelled, []);
|
||||
|
||||
now += 1500;
|
||||
await pollTransfer("example", 1);
|
||||
assert.deepEqual(cancelled, [1]);
|
||||
assert.equal(reloads, 1);
|
||||
});
|
||||
|
||||
test("settings transfer polling recovers from a temporary error or an invalid JSON response", async () => {
|
||||
const start = settingsSource.indexOf("async function fetchTransferJob(");
|
||||
const end = settingsSource.indexOf("async function loadTransferNodes(", start);
|
||||
const completed = { status: "done", finishedAt: 12000, message: "Transfer complete; source cleanup pending" };
|
||||
const responses = [
|
||||
{ ok: false, status: 503, headers: new Map() },
|
||||
{ ok: true, json: async () => { throw new SyntaxError("truncated JSON"); } },
|
||||
{ ok: true, json: async () => ({ job: completed }) },
|
||||
];
|
||||
const events = [];
|
||||
let now = 1000;
|
||||
const pollTransfer = vm.runInNewContext(`${settingsSource.slice(start, end)}\npollTransfer;`, {
|
||||
transferViewVersion: 1, transferPollTimer: 17, transferPollRetryAt: 0,
|
||||
Date: { now: () => now }, fetch: async () => responses.shift(),
|
||||
setTransferProgress: job => events.push(job),
|
||||
setTransferFeedback: message => events.push(message),
|
||||
clearInterval: timer => events.push(timer),
|
||||
loadServers: () => events.push("reload"),
|
||||
});
|
||||
await pollTransfer("example", 1);
|
||||
now += 5000;
|
||||
await pollTransfer("example", 1);
|
||||
assert.deepEqual(events, []);
|
||||
now += 5000;
|
||||
await pollTransfer("example", 1);
|
||||
assert.deepEqual(events, [completed, completed.message, 17, "reload"]);
|
||||
});
|
||||
|
||||
test("settings transfer modal starts polling when its first lookup is throttled and the modal is still open", async () => {
|
||||
const start = settingsSource.indexOf("async function openTransferModal(");
|
||||
const end = settingsSource.indexOf("if (transferModalClose)", start);
|
||||
assert.ok(start >= 0 && end > start);
|
||||
const polls = [];
|
||||
const sandbox = {
|
||||
transferViewVersion: 0,
|
||||
transferModalTitle: null,
|
||||
transferModalSubtitle: null,
|
||||
transferPollTimer: null,
|
||||
showTransferModal() {},
|
||||
setTransferFeedback() {},
|
||||
setTransferProgress() {},
|
||||
loadTransferNodes: async () => {},
|
||||
fetchTransferJob: async () => undefined,
|
||||
pollTransfer: (server) => polls.push(server),
|
||||
setInterval: (poll, wait) => { assert.equal(wait, 1500); return poll; },
|
||||
};
|
||||
const openTransferModal = vm.runInNewContext(`${settingsSource.slice(start, end)}\nopenTransferModal;`, sandbox);
|
||||
|
||||
await openTransferModal("active");
|
||||
sandbox.transferPollTimer();
|
||||
assert.deepEqual(polls, ["active"]);
|
||||
|
||||
sandbox.transferPollTimer = null;
|
||||
let completeLookup;
|
||||
const lookup = new Promise((resolve) => { completeLookup = resolve; });
|
||||
const lookupReady = new Promise((resolve) => {
|
||||
sandbox.fetchTransferJob = () => { resolve(); return lookup; };
|
||||
});
|
||||
const closingModal = openTransferModal("closed");
|
||||
await lookupReady;
|
||||
sandbox.transferViewVersion += 1;
|
||||
completeLookup(undefined);
|
||||
await closingModal;
|
||||
assert.equal(sandbox.transferPollTimer, null);
|
||||
});
|
||||
|
||||
test("a late node list and its transfer actions cannot target a different open dialog", async () => {
|
||||
const start = settingsSource.indexOf("let transferViewVersion = 0;");
|
||||
const end = settingsSource.indexOf("if (transferModalClose)", start);
|
||||
assert.ok(start >= 0 && end > start);
|
||||
const requests = [];
|
||||
const list = { innerHTML: "", appendChild(item) { this.item = item; } };
|
||||
const sandbox = {
|
||||
transferNodeList: list,
|
||||
transferPollTimer: null,
|
||||
transferPollRetryAt: 0,
|
||||
transferModalOverlay: null,
|
||||
transferModalTitle: null,
|
||||
transferModalSubtitle: null,
|
||||
transferFeedback: null,
|
||||
transferProgress: null,
|
||||
escapeHtml: String,
|
||||
document: { createElement: () => ({ dataset: {}, querySelector: () => null, addEventListener() {} }) },
|
||||
fetch: (url) => url === "/api/nodes"
|
||||
? new Promise((resolve) => requests.push(resolve))
|
||||
: Promise.resolve({ ok: true, json: async () => ({ job: null }) }),
|
||||
sendServerRowActionWithGuards: () => assert.fail("a stale dialog must not submit a transfer"),
|
||||
};
|
||||
vm.runInNewContext(settingsSource.slice(start, end), sandbox);
|
||||
const old = sandbox.openTransferModal("alpha");
|
||||
const active = sandbox.openTransferModal("bravo");
|
||||
const nodes = (id) => ({ ok: true, json: async () => ({ nodes: [{ id, online: true }] }) });
|
||||
requests[1](nodes("bravo-node"));
|
||||
await active;
|
||||
requests[0](nodes("alpha-node"));
|
||||
await old;
|
||||
assert.equal(list.item.dataset.id, "bravo-node");
|
||||
await sandbox.startTransfer("alpha", "alpha-node", 1);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 4. settings.js install pollers — 429 is backoff, not failure
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Extract one install-poller closure from settings.js by occurrence (0 =
|
||||
// pgAdmin, 1 = MongoDB): the slice runs from the failure-counter declaration
|
||||
// through the poller and its kick-off setTimeout.
|
||||
function extractPoller(occurrence) {
|
||||
const anchor = "let consecutivePollFailures = 0;";
|
||||
let start = -1;
|
||||
for (let i = 0; i <= occurrence; i++) {
|
||||
start = settingsSource.indexOf(anchor, start + 1);
|
||||
assert.ok(start >= 0, `poller occurrence ${i} not found`);
|
||||
}
|
||||
const kicker = "setTimeout(pollProgress, 2000);";
|
||||
const kickerIdx = settingsSource.indexOf(kicker, start);
|
||||
assert.ok(kickerIdx > start, "kicker not found after the poller");
|
||||
const end = settingsSource.indexOf("} catch (err) {", kickerIdx);
|
||||
assert.ok(end > kickerIdx, "outer catch not found after the kicker");
|
||||
return settingsSource.slice(start, end);
|
||||
}
|
||||
|
||||
function makePollerHarness(copy) {
|
||||
const timers = [];
|
||||
const feedback = [];
|
||||
const queue = [];
|
||||
const harness = {
|
||||
timers,
|
||||
feedback,
|
||||
pollUrl: null,
|
||||
feed: (r) => queue.push(r),
|
||||
};
|
||||
const fetchStub = async (url) => {
|
||||
harness.pollUrl = url;
|
||||
const r = queue.shift();
|
||||
assert.ok(r, `no queued poll response for ${url}`);
|
||||
return {
|
||||
ok: r.status >= 200 && r.status < 300,
|
||||
status: r.status,
|
||||
headers: { get: (name) => (r.headers || {})[String(name).toLowerCase()] ?? null },
|
||||
json: async () => r.body || {},
|
||||
};
|
||||
};
|
||||
const sandbox = {
|
||||
fetch: fetchStub,
|
||||
setTimeout: (fn, ms) => { timers.push({ fn, ms }); return timers.length; },
|
||||
clearTimeout: () => {},
|
||||
console: { error: () => {}, log: () => {}, warn: () => {} },
|
||||
// Closure variables the poller reads from its enclosing setup handler.
|
||||
jobId: "test-job-1",
|
||||
password: "test-password",
|
||||
// feedback records ERROR feedback only — the completed path's success
|
||||
// toast ("setup complete!") is not a failure and must not count.
|
||||
showPgAdminFeedback: (msg, isError) => { if (copy === "pgadmin" && isError) feedback.push({ msg, isError }); },
|
||||
showMongoDBFeedback: (msg, isError) => { if (copy === "mongodb" && isError) feedback.push({ msg, isError }); },
|
||||
closePgAdminSetupModal: () => {},
|
||||
closeMongoDBSetupModal: () => {},
|
||||
loadPgAdminStatus: () => {},
|
||||
loadMongoDBStatus: () => {},
|
||||
progressText: null,
|
||||
progressPercent: null,
|
||||
progressFill: null,
|
||||
progressContainer: null,
|
||||
pgadminSetupSave: null,
|
||||
pgadminSetupCancel: null,
|
||||
pgadminToggle: null,
|
||||
mongodbSetupSave: null,
|
||||
mongodbSetupCancel: null,
|
||||
mongodbToggle: null,
|
||||
pendingMongoPassword: null,
|
||||
document: { createElement: () => ({ classList: { add() {}, remove() {} }, style: {}, remove() {} }), body: { appendChild() {} } },
|
||||
};
|
||||
const source = extractPoller(copy === "pgadmin" ? 0 : 1);
|
||||
vm.runInContext(source, vm.createContext(sandbox), { filename: `settings.js[${copy}-poller]` });
|
||||
// The kicker already queued the first poll.
|
||||
assert.equal(timers.length, 1, "the poller kick-off is queued");
|
||||
return harness;
|
||||
}
|
||||
|
||||
const RUNNING = { status: "running", progress: 40, message: "Installing..." };
|
||||
const COMPLETED = { status: "completed", progress: 100, message: "Installation complete!" };
|
||||
|
||||
// Runs EXACTLY `steps` poll steps. Deterministic by construction: every
|
||||
// poller step consumes exactly one queued fetch response (the kick-off
|
||||
// included), so `steps === responses + 1` while the poll is still running.
|
||||
async function runPollSteps(harness, steps) {
|
||||
let done = 0;
|
||||
while (done < steps) {
|
||||
const t = harness.timers.shift();
|
||||
assert.ok(t, `timer queue exhausted after ${done} of ${steps} steps`);
|
||||
done += 1;
|
||||
await t.fn();
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
for (const copy of ["pgadmin", "mongodb"]) {
|
||||
test(`[${copy}] a 429 poll response does NOT consume the failure budget — 4 throttles then success completes the install`, async () => {
|
||||
const harness = makePollerHarness(copy);
|
||||
// 4 consecutive 429s (each would have incremented consecutivePollFailures
|
||||
// under the old code and thrown on the 4th), then success.
|
||||
for (let i = 0; i < 4; i++) harness.feed({ status: 429, headers: { "retry-after": "2" } });
|
||||
harness.feed({ status: 200, body: RUNNING });
|
||||
harness.feed({ status: 200, body: COMPLETED });
|
||||
|
||||
const ran = await runPollSteps(harness, 6);
|
||||
assert.equal(ran, 6, "polls kept running across the throttles (kick-off + 5 re-polls)");
|
||||
assert.deepEqual(harness.feedback, [], "the running install must NOT be marked failed by its own 429s");
|
||||
assert.equal(harness.timers.length, 1, "only the completion-timeout timer remains (polling stopped cleanly)");
|
||||
});
|
||||
|
||||
test(`[${copy}] Retry-After is honored (numeric seconds, clamped 2-15s) with a 5s default`, async () => {
|
||||
const harness = makePollerHarness(copy);
|
||||
const delays = [];
|
||||
harness.feed({ status: 429, headers: { "retry-after": "8" } });
|
||||
harness.feed({ status: 429, headers: {} });
|
||||
harness.feed({ status: 429, headers: { "retry-after": "1" } });
|
||||
harness.feed({ status: 429, headers: { "retry-after": "60" } });
|
||||
harness.feed({ status: 200, body: COMPLETED });
|
||||
|
||||
// Poll → observe the delay the next poll was scheduled with.
|
||||
for (let i = 0; i < 4; i++) {
|
||||
await runPollSteps(harness, 1);
|
||||
delays.push(harness.timers[0].ms);
|
||||
}
|
||||
await runPollSteps(harness, 1);
|
||||
assert.deepEqual(delays, [8000, 5000, 2000, 15000], "Retry-After honored; missing → 5s; clamped into [2s, 15s]");
|
||||
assert.deepEqual(harness.feedback, [], "backoff never fails the install");
|
||||
});
|
||||
|
||||
test(`[${copy}] the preserved pin: 4 consecutive NON-429 failures still mark the install failed exactly as today`, async () => {
|
||||
const harness = makePollerHarness(copy);
|
||||
for (let i = 0; i < 4; i++) harness.feed({ status: 502 });
|
||||
await runPollSteps(harness, 4);
|
||||
assert.deepEqual(
|
||||
harness.feedback,
|
||||
[{ msg: "Installation failed: Progress check failed (HTTP 502)", isError: true }],
|
||||
"non-429 failure semantics unchanged"
|
||||
);
|
||||
});
|
||||
|
||||
test(`[${copy}] 404 stays terminal exactly as today`, async () => {
|
||||
const harness = makePollerHarness(copy);
|
||||
harness.feed({ status: 404 });
|
||||
await runPollSteps(harness, 1);
|
||||
assert.deepEqual(harness.feedback, [{ msg: "Installation failed: Installation progress record not found (HTTP 404)", isError: true }]);
|
||||
});
|
||||
|
||||
test(`[${copy}] the bounded 429 backoff counter: 30 consecutive throttles are ridden out, the 31st throws`, async () => {
|
||||
const harness = makePollerHarness(copy);
|
||||
for (let i = 0; i < 30; i++) harness.feed({ status: 429, headers: { "retry-after": "2" } });
|
||||
const rodeOut = await runPollSteps(harness, 30);
|
||||
assert.equal(rodeOut, 30, "30 consecutive throttles ride out with backoff");
|
||||
assert.deepEqual(harness.feedback, [], "30 throttles must NOT mark the install failed (the old code failed at the 4th)");
|
||||
harness.feed({ status: 429, headers: { "retry-after": "2" } });
|
||||
await runPollSteps(harness, 1);
|
||||
assert.deepEqual(
|
||||
harness.feedback,
|
||||
[{ msg: "Installation failed: Progress check failed (HTTP 429)", isError: true }],
|
||||
"a permanently-throttled panel must not poll forever"
|
||||
);
|
||||
});
|
||||
|
||||
test(`[${copy}] a non-429 failure resets the consecutive-429 counter (strictly consecutive)`, async () => {
|
||||
const harness = makePollerHarness(copy);
|
||||
for (let i = 0; i < 29; i++) harness.feed({ status: 429, headers: { "retry-after": "2" } });
|
||||
harness.feed({ status: 500 }); // resets the throttle counter, burns failure budget #1
|
||||
for (let i = 0; i < 2; i++) harness.feed({ status: 429, headers: { "retry-after": "2" } }); // fresh counter — no throw
|
||||
harness.feed({ status: 200, body: COMPLETED });
|
||||
await runPollSteps(harness, 33);
|
||||
assert.deepEqual(harness.feedback, [], "29 + reset + 2 throttles must not trip the 30-consecutive bound");
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 5. Wire pins — flag coupling and exemption coupling are intentional
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("the exemption is documented at the shared list (same brake system, never double-budgeted)", () => {
|
||||
const anchor = indexOfOrThrow(indexSource, "const RATE_LIMIT_EXEMPT_PATTERNS = [");
|
||||
const block = indexSource.slice(anchor, indexOfOrThrow(indexSource, "function isRateLimitExempt(path, method) {"));
|
||||
assert.ok(block.includes("adpanel:progress-poll-budget"), "the exempt list documents why the poll families moved out of the generic budgets");
|
||||
assert.ok(block.includes("progressPollRateLimiter"), "the exempt list names the limiter that owns the budget instead");
|
||||
});
|
||||
Reference in new issue
Block a user